Reputation: 2176
I've tried implementing the answers I've found but am not sure I understand as they don't work.
I have this JSFiddle: http://jsfiddle.net/cmscss/Gdn7Y/10/
In that fiddle, I was trying to bind a click event to the body if .expand also had a class of .expanded like this:
if ($(expand).hasClass(".expanded")) {
$('body').click(function () {
$(expand).children(".expand-content").toggle();
$(expand).toggleClass("expanded");
});
}
What's the best way to toggle the .expanded div if the visitor clicks outside?
Plus I'd welcome any other suggestions on the code as this is almost the first thing I've done with jQuery/JavaScript.
Cheers
Upvotes: 2
Views: 120
Reputation: 4578
Try this code:
$(document).ready(function() {
// cache classes
var expand = $(".expand"),
trigger = $(".expand-trigger");
// if .expand is on the page
if (expand.length > 0) {
$(trigger).click(function () {
expand.children(".expand-content").slideToggle();
expand.toggleClass("expanded");
return false; // stops browser jumping to top when triggers are clicked
});
}
$('.expand-content').click(function(e){
e.stopPropagation();
});
$('body').click(function () {
if (expand.hasClass("expanded")) {
expand.children(".expand-content").slideToggle();
expand.toggleClass("expanded");
}
});
});
Here is JSFiddle
Upvotes: 3