Skip to content Skip to sidebar Skip to footer

Why Is Javascript Button Not Working?

The effect I am trying to achieve is that when I click a button (called about), one of the div (id=homepage) gets hidden and another div (id=intro_page, which was previously hidden

Solution 1:

The parameter to getElementById() is a string. So assuming you did not set some (global) variables homepage and intro_page, your clicked_about() function should look like this:

functionclicked_about(){
   document.getElementById('homepage').style.display = 'none';
   document.getElementById('intro_page').style.display = 'block';
}

Solution 2:

I did some changes in your code check this :)

window.onload = function(){
    var mybutton = document.getElementById("mybutton");
    mybutton.addEventListener("click",function(){
       
       document.getElementById("homepage").style.display = 'none';
       document.getElementById("intro_page").style.display = 'block';
   });
}
<buttonid="mybutton"type="button">About</button><divid="homepage">
     content
</div><divid="intro_page"style="display: none"><h1id="intro_page_caption"> About Me </h1><divid="intro_main_text"><p> I enjoy reading, swimming, jogging, painting and exploring. </p></div><divclass="intro_pic1"><figure><imgsrc="img/my_picture.jpg"alt="My Picture"height="250"><figcaption>My Picture</figcaption></figure></div></div>

Solution 3:

Just enclose the ids in quotes:

functionclicked_about(){
   document.getElementById("homepage").style.display = 'none';
   document.getElementById("intro_page").style.display = 'block';
}

Otherwise homepage and intro_page are variables, and therefore undefined, unless you previously defined them elsewhere.

Solution 4:

The function getElementById accepts parameter in string format. Wrap you Id in " and it will work

functionclicked_about() {
  document.getElementById("homepage").style.display = 'none';
  document.getElementById("intro_page").style.display = 'block'; // missing quotes here
}
<buttononclick="javascript:clicked_about()"type="button">About</button><divid="homepage">
  content
</div><divid="intro_page"style="display: none"><h1id="intro_page_caption"> About Me </h1><divid="intro_main_text"><p>I enjoy reading, swimming, jogging, painting and exploring.</p></div><divclass="intro_pic1"><figure><imgsrc="img/my_picture.jpg"alt="My Picture"height="250"><figcaption>My Picture</figcaption></figure></div></div>

Solution 5:

Very simple

document.getElementById("btn").onclick=function(){clicked_about();};

with

<button id="btn">About</button>

here is a JFiddle https://jsfiddle.net/upujp2q9/

Post a Comment for "Why Is Javascript Button Not Working?"