Why Won't My Button Do The Function When I Click It It. It Should Toggle The Text
Happy Bir
Solution 1:
there are no script tags add the javascript tags.
<script type="text/javascript"> your code </script>
Solution 2:
The issue stems from you declaring the function using the function
keyword. Usually this is fine, but I find that it's easier to work with javascript functions called by HTML as functions that have been assigned to a variable. If you use ES6 arrow syntax, you'll both be using the latest standards and binding the function to a variable. Try rewriting the function code like so:
<script>
myFunction = () => {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script><buttononclick="myFunction()">Try it</button><divid="myDIV"style="display: none"><h3id="h3"> Happy Birthday Tiffany!</h3></div>
Solution 3:
Your JS function must be declared before your button. And must be enclosed in <script> </script>
tags
Solution 4:
You could use addEventListner()
insted of inline HTML onclick()
. Try this:
var x = document.getElementById("myDIV");
document.getElementById("myBtn").addEventListener('click', function() {
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
#myDIV {
border: 1px solid black;
padding: 3px;
}
<buttontype="button"id="myBtn">Show</button><divid="myDIV"style="display: none;">Show the content</div>
Notice that x.style.display
detect the inline style HTML attribute. Becouse of that, if you use a separate css file to styling the div, you'll need twice click for the first time...
Solution 5:
If you are trying to inline your code within the webpage then yes you will need to make sure you classify what type of code you are using. <style></style>
is for CSS and <script></script>
is for Javascript.
It seems like you are trying to perform a simple hide/show script. One thing that you should work on is efficiency of your code. The chunky code in your question can be shortened to this:
functiontoggleHide() {
var element = document.getElementById("myDIV");
element.classList.toggle("hide");
}
.hide {
display: none;
}
<buttononclick="toggleHide()">Try it</button><divid="myDIV">This is a DIV element.</div>
Here is what it looks like inline:
<style>.hide {
display: none;
}
</style><buttononclick="myFunction()">Try it</button><divid="myDIV">This is a DIV element.</div><script>functionmyFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("hide");
}
</script>
Post a Comment for "Why Won't My Button Do The Function When I Click It It. It Should Toggle The Text"