Krystov Jonazon
Krystov Jonazon

Reputation: 39

onclick behaves oddly - refreshes page instead of displaying content

Here is my code, shortened for ease of access;

HTML

<a  onclick="showHideDiv('bio')" target='_self'>
  bio
  <div id="bio" class="shadowScreen" style="display: none;">
    <p class="showBio">
      Bio!
    </p>
  </div>
</a>

Javascript:

var curDiv;

function showHideDiv(id){
  if (curDiv!==null){
    document.getElementById(curDiv).style.display="none";
  }
  document.getElementById(id).style.display="inline";
  curDiv=id;
}

CSS:

.shadowScreen{
  -moz-box-shadow: 0 0 30px 5px;
  -webkit-box-shadow: 0 0 30px 5px;
}
.showBio{
  background-color: white;
  position:fixed;
  top:50%;
  left:50%;
  transform: translate(-50%, -50%);
}

When the 'a' element is clicked "showDiv(div)" is supposed to send a function call to JS which alters "display:none;" to "display:inline;". The HTML will now have the 'div' element which has the class "shadowScreen" which darkens the entire screen. I then have a 'p' element which centers a box on the screen and displays "bio!". But, it's not doing that, and I can't figure out why naht. I'm not the greatest with the Netbeans debugger, so I can't tell exactly what it's saying ;-;

If you need further clarification, just ask! I'll be more than happy to help you help me.

Upvotes: 0

Views: 65

Answers (3)

Roberto14
Roberto14

Reputation: 689

You should remove target and add "#" to href param as suggested.

<a href="#" onclick="showHideDiv('bio')">Bio</a>

Regarding your javascript code, try to initialise your curDiv variable with null.

var curDiv = null;

Upvotes: 1

Shaggy
Shaggy

Reputation: 6796

Firstly, you'll need to give your anchor tag a href attribute to make it valid. I'd suggest using the ID of the div you're toggling - #bio - or simply just #.

Next, you need to prevent the default action of your anchor tag in order to stop it executing the link you used in the href attribute. To do so, you need to add the following line to the end of your JavaScript function:

return false;

Upvotes: 0

Muhammad Bilal
Muhammad Bilal

Reputation: 2134

I think its redirecting because of the a tag.

You should replace:

<a  onclick="showHideDiv('bio')" target='_self'>

with

<a href="javascript:void(0);"  onclick="showHideDiv('bio')" target='_self'>

Upvotes: 0

Related Questions