0

I have a div with id="menu" in my index.html file and I want to hide it using jQuery. In my script.js I wrote:

window.onload = function() { prepareEventHandlers(); } function prepareEventHandlers() { var hideDiv = $("#menu"); var crtButton = $("#hide"); crtButton.onclick = function() { hideDiv.hide(); }; } 

But when I press the button on the webpage the div is still there, the only way that works is if in the index.html I write:

 <button type="button" onclick="$('#menu').hide()" id="hide">HideDiv</button> 

but I don't want to use it since it is bad style, so how can I make this work using my script.js code?

1
  • Like Lucas mentioned, crtButton is a jQuery object. You can either use his code or in your code use crtButton[0].onclick Commented Jul 27, 2014 at 17:21

2 Answers 2

1

crtButton.onclick won't work because crtButton is a jQuery object, not a DOM element.

Do this instead:

$(document).ready(function() { $("#hide").on("click", function() { $("#menu").hide(); }); } 

This is the jQuery way. Note that I replaced window.onload with a $(document).ready callback, which will be called as soon as the DOM is ready (sooner than onload). I also used the .on() function to bind to the event.

Sign up to request clarification or add additional context in comments.

6 Comments

or you can do $(crtButton).click(...
crtButton is already a jQuery object. You don't have to re-query it crtButton.click(function(){}) will work. That being said, .on('click', function(){}) is the newer and preferred method
Unless that button is dynamic theres no need to use .on, .click will do the same thing
I didn't say it won't work. Its just better as it works with dynamic elements and can be easily unbound
@tymeJV what do you mean by dynamic?
|
0

Go with Lucas' answer or modify your own code

crtButton is a jquery object so it doesn't have onclick property. Edit onclick property of the DOM element instead (which is crtButton[0])

Or just skip jQuery and use getElementById

 window.onload = function() { prepareEventHandlers(); } function prepareEventHandlers() { var hideDiv = document.getElementById("menu"); var crtButton = document.getElementById("hide"); crtButton.onclick = function() { hideDiv.style.display = 'none' }; } 

4 Comments

I tried it the way you suggested, but I get a type error saying that hideDiv is not a function, it is thrown on line hideDiv.hide(); any idea why?
but wouldn't display 'none' yank it out of the DOM tree completely? I'm trying to avoid that since I might to bring it back if requested by the user.
it just hides it. you can do hideDiv.style.display = '' to show it back
You probably should stick to jQuery IMO, and learn it's API. It will save you a lot of time and effort on the long run.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.