karto
karto

Reputation: 3658

Javascript onclick hide div

I want to hide this warning div using javascript inside it.

I'm i getting the javascript right? I want to hide/close the div when i click on the close icon (images/close_icon.gif)

<div>
  <strong>Warning:</strong>
  These are new products
  <a href='#' class='close_notification' title='Click to Close'>
    <img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="this.close" />
  </a
</div>

Upvotes: 35

Views: 228123

Answers (4)

Amir Savand
Amir Savand

Reputation: 384

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

Upvotes: 27

Andrei
Andrei

Reputation: 4237

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"

Upvotes: 10

Coin_op
Coin_op

Reputation: 10718

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:

this.parentNode.style.display = 'none';

To remove it you use removeChild

this.parentNode.parentNode.removeChild(this.parentNode);

If you had a library like jQuery included then hiding or removing the div would be slightly easier:

$(this).parent().hide();
$(this).parent().remove();

One other thing, as your img is in an anchor the onclick event on the anchor is going to fire as well. As the href is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false;

Upvotes: 52

Chris Sobolewski
Chris Sobolewski

Reputation: 12925

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

Upvotes: 17

Related Questions