Why can I not hide an element on click using jQuery? - javascript

I want to let a div show and disappaer with jquery and css.
The code does not work:
HTML
<html>
<head>
</head>
<body>
<div class="box" id="b1">
click to show content
<div class="content">
here is content here is content here is content
<div class="button" id="b2">remove content</div>
</div
</body>
</html>
jQuery
$(document).ready(function() {
$('#b1').click(function() {
$('.content').css({
"display": "block"
});
});
$('#b2').click(function() {
$('.content').css({
"display": "none"
});
});
});
Demo: http://jsfiddle.net/jTgRF/41/

The problem is that you don't stop the event from propagating.
When you click the button it actually hide the element at first, but the event propagate up to the parent element, at which you catch the click and show it again. It goes so fast it looks like nothing is happening, but actually when you click on #b2, the elements get hidden, the event then bubble up to the parent #b1, to which you have attached click-event listener to show the content.
Therefor, you need to use .stopPropagation() on #b2.
$(document).ready(function(){
$('#b1').click(function(){
$('.content').show();
});
$('#b2').on("click", function(e){
$('.content').hide();
e.stopPropagation();
});
});
What you need to do is to pass the click event to the call-backfunction (declared e in my example) and then call stopPropagation() on it to make sure that it doesn't bubble up to the parent element.
Here is a working example: http://jsfiddle.net/jTgRF/64/
Note I use .show() and .hide(), which is exactly the same as what you do with .css(), but is more readable in my opinion.
Edit:
As noted by Venu in his answer, the content will show if you click on the black-area as well, not just the "show content"-text. The easiest way to solve that would be to just move the id="b1" attribute from the div with class content and put it on the a-element instead.
See my updated fiddle: http://jsfiddle.net/jTgRF/65/

since, you are attaching an event for an element which is not available in dom, event wont get attached to the element. Use live
$('#b2').live('click', function(){
$('.content').css({"display":"none"});
});
Attach an event handler for all elements which match the current selector, now and in the future.
EDIT
1)Use on instead of live as Live is deprecated.
2) There is one more issue with your css. you have set height to 150px for box class. so if you click on black area also, event gets fired.
So move the b2 element outside b1, this would solve the event propagation to the parent-element also.

You need to change the button click handler to
$('#b2').click(function(e){
e.stopPropagation();
$('.content').css({"display":"none"});
});
You need to add event.stopPropagation() Or click event will be propagated to the parent div and .content will be hidden immediately again.
Demo: http://jsfiddle.net/joycse06/jTgRF/56/
You should use jQuery .show() and .hide() to show/hide elements.

Venu's anwser works but live() is depracated.
You should use on() instead :
jQuery .on function for future elements, as .live is deprecated
Code
$(document).ready(function(){
$('#b1').click(function(){
$('.content').css({"display":"block"});
});
$(document).on('click', '#b2', function(){
$('.content').css({"display":"none"});
});
});
Hope this helps

Related

click event is not working for dynamically created button

I am using google translator which creates dynamically translator bar,it has show original button (click on below image link).
I want to fire click event of "show original" button manually using javascript or jquery but is is not working, see some of the code snippets that i tried.
$("#myBtn").click(function(){
$("#\\:1\\.restore").click();
//or
$("#\\:1\\.restore").on('click');
//or
$("#\\:1\\.restore").trigger('click',jQuery.Event( "click" ));
//or
document.getElementById(':1.restore').click();
})
imageURL: http://1drv.ms/1KhfLbo
The event on myBtn is not fired and your event handler is not working.
For dynamically added elements use event delegation.
$(document).on('click', '#myBtn', function() {
// Your Code Here
});
To trigger event:
$("#\\:1\\.restore").trigger('click');
You need delegate from a container such as document
$(document).on('click', '#\\:1\\.restore', function(){...}));
I want to fire click event of "show original" button manually
Use
$('#\\:1\\.restore').trigger('click')
or
$('#\\:1\\.restore').click();//with no parameters
I got the answer.
Actually translate bar was inside iframe tag, so we need to select iframe (container) then any element inside that.
$("#myBtn").click(function(){
$('#\\:1\\.container').contents().find('#\\:1\\.restore').click();
});

How to Show/Hide div when hovering to any Link

I am facing one small Issue in displaying/hiding any div on hovering any anchor tag.
Currently I tried with Mouseenter and MouseLeave functions but Its not smooth.
Clickable Link:<a class="clickmeToSeeDiv" href="##"></a>
JS code:
$('.clickmeToSeeDiv').live("mouseenter",function(){
$('.leftborderActive').show();
});
$('.clickmeToSeeDiv').live("mouseleave",function(){
$('.leftborderActive').hide();
});
Above code sometime works sometimes not.
Please suggest if you all have any Idea or a better solution.
Thanks
Sham
live event is deprecated, use .on() instead (Attach an event handler function for one or more events to the selected elements).
Try this:
$(document).ready(function(){
$(".leftborderActive").hide(); // hide div on DOM ready
$( ".clickmeToSeeDiv" ).mouseenter(function() { // anchor mouseover event
$(".leftborderActive").show(); // show div
}).mouseleave(function() { //anchor mouseleave event
$(".leftborderActive").hide(); //hide div
});
});
DEMO
or
$(document).ready(function(){
$(".leftborderActive").hide();
$(document).on('mouseenter mouseleave','.clickmeToSeeDiv',function(){
$('.leftborderActive').toggle();
});
});
the method 'live' is deprecated, use 'on' instead.
$(document).on('mouseenter mouseleave', '.clickToSeeDiv', OnDivClick);
function OnDivClick(){
$('.clickToSeeDiv').toggle();
}
You could try JQuery's animate functions or set a timer on the show and hide methods so that they make the div operate a little more smoothely.
Also, make sure to cancel any previous events when you call the enter or leave methods so that the animations don't stack.

A way to remove click events for element

I have an element #foo and it has click event on it. Element #foo is in element #bar which also has click event on it.
<div id="bar">
<div id="foo" />
</div>
When #foo is clicked, #bar event gets called and #foo event gets ignored. That's now what I want.
I'm looking for a way to remove all click events from #foo element except my just set event and all events that are on parents for #foo.
Edit: Here is jsFiddle demo. I want 2nd event to get called before 1st event.
Edit #2: Here is my code with your suggestions. Doesn't work.
If you have a click event on foo and you dont want it to bubble you could do the following:
$("#foo").on('click', function(e){
e.preventDefault();
e.stopPropagation(); //this line will stop the click bubbling up the tree.
});
Use stopPropagation function, see an example:
$("#foo").click(function(e) {
e.stopPropagation();
})
try this
$('#foo').click(function(e){
e.preventDefault();
e.stopPropagation();
$('#bar').trigger('click');
});

how to select the rest of a div?

i got a problem
<div id='parent'>
<div id='child'>
</div>
</div>
what i want is when the child is clicked addClass,and when the rest of parent is clicked removeClass,so when i try to do
$('#child').click(function(){
$(this).addClass();
})
$('#parent').click(function(){
$('#child').removeClass();
})
its not working i think its because the child is actually inside the parent,so when the child is clicked the parent clicked right?
so how can i do that?
try this:
$('#child').click(function(evt){
evt.stopPropagation();
$(this).addClass("myClass");
});
You could use event.stopPropagation to prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('#child').click(function(e){
e.stopPropagation();
$(this).addClass();
});
Several users have already suggested a good solution - here's an explanation of why it works:
When you click an HTML element (actually a DOM object...), the click event "bubbles" all the way up to the root element. For example, a click in #child also triggers a click in #parent, as you expected.
To stop this behavior, you need to call .stopPropagation() on the click event - that will tell the browser that you do not want the event to propagate, but keep it "local". Basically, when you've handled it here, you're done with it and don't want to see it again.
Conveniently, jQuery event handlers take the event as the first argument, so if you assign any function with the signature function (e) { ... }, you can stop event propagation by e.stopPropagation(); as others have suggested. In your case, you want
$('#child').click(function(e){
$(this).addClass();
e.stopPropagation();
});
$('#parent').click(function(){
$('#child').removeClass();
});

jQuery Selector : select a box but not an element inside the box

Let's says I have the following code :
<div class="body">
Click me and it will work.
<div class="head">Click me and nothing will happen.</div>
</div>
I want to display the "it works" when you click inside the .body div but not inside the .head div. How can I do this?
With this code, the log appears even if you click on head:
<script>
$('.body').click(function(){console.log('it works !');});
</script>
$('.body').click(function(e){
if($(e.target).hasClass('body'))
console.log('it works !');
});
Event bubbling is causing your troubles. Essentially, the event handler for your 'head' class would capture the click and then bubble that event up to your 'body' handler because there are nested.
Here is an excellent primer on event bubbling, how it works, and how to control event bubbling.
Here is working jsFiddle example for you to test.
Its called event bubbling. When you click on "head" div you also click on "body" div.
You need to add:
$('.head').click(function(event){event.stopPropagation()});
to prevent event bubbling.
This is the general solution:
$('.body').click(function(e){
if(e.target === this) {
console.log('it works !');
}
});
Solved similar question on stackoverflow:
Select only parent, exclude everything else while click()

Categories

Resources