Reputation: 3652
I have (what I'm sure is) a beginner question about JQuery.
I'm trying to make a div popup when an image is clicked. (There are multiple instances of this on one page, btw.)
However, the div doesn't close when 'close' is clicked.
Here's the JQuery...
$(document).ready(function() {
// Set up bubble CSS when page is loaded so bubble info is hidden unless user acts.
// If JavaScript is turned off bubble info displays normally.
//
//
$('.bubble_wrapper').css('position', 'relative');
$('.bubble_info').css({
position: 'absolute',
display: 'none'
});
$('.bubble_close').css('display', 'block');
});
$(function() {
var counter = 1;
$('.bubble_wrapper').each(function() {
var trigger = $('#bubble_trigger'+counter, this);
var popup = $('#bubble_info'+counter, this);
$([trigger.get(0), popup.get(0)]).click(function() {
$('.bubble_info').css('display', 'none');
popup.css('display', 'block');
});
$('.bubble_close').click(function() {
$('.bubble_info').css('display', 'none');
});
counter += 1;
});
});
And here's the html (I'm working in Rails, btw)...
<section id="latest_articles">
<ul>
<% id_counter = 1 %>
<% @articles.each do |article| %>
<li class="bubble_wrapper">
<%= image_tag(article.image_url(:thumb), :class => "bubble_trigger", :id => "bubble_trigger"+id_counter.to_s) if article.image? %>
<div class="bubble_info" id=<%= "bubble_info"+id_counter.to_s %> >
<h1><%= link_to article.title, article %></h1>
<p><%= article.description %></p>
<a class="bubble_close">Close</a>
</div>
</li>
<% id_counter += 1 %>
<% end %>
</ul>
</section>
Thanks in advance!
Upvotes: 0
Views: 87
Reputation: 123739
Just add this, event.stopPropagation to prevent the click click from bubbling up to its parent.
$('.bubble_close').click(function(e) {
e.stopPropagation();
$('.bubble_info').css('display', 'none');
});
What happened here is the click event attached to the parent $([trigger.get(0), popup.get(0)])
opens up the div , but the close
button is inside the div which has its own click event. So clicking on close div, its click event propagated to its parent. So it closes and opens again. stopPropagation
prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
On a different note you can use .show() and .hide() instead of making display:block and hide
manually assigning css properties..
popup.css('display', 'block');
instead you can use
popup.show();
similarly
$('.bubble_info').css('display', 'none');
you can use
$('.bubble_info').hide();
Upvotes: 3