Jquery click event targeting more than one element - javascript

Codepen is here
I have two triggers on an image. General behaviour:
When I click a trigger, it should reveal a small context box (got this working)
When I click outside of the context box OR the trigger, it should disappear (got this working)
When I click another trigger, if there is another trigger/context box that is already active/open, it should close the other one and open the recently click one (not working)
Here's the html:
<span class='pulse-button' id="button-1"></span>
<div class="content-box context-closed tabs" id="tabs1">
</div>
Here's my jQuery:
$(function(){
$(".pulse-button").click(function(e){
e.stopPropagation();
if( $(".pulse-button").not(this).hasClass("pulse-button-active")){
$(".pulse-button").not(this).removeClass("pulse-button-active");
$(".pulse-button").not(this).next().addClass("context-closed");
}else{
$(this).addClass("pulse-button-active");
$(this).next().removeClass("context-closed");
};
});
$("body").click(function(evt){
if(evt.target.class == "content-box")
return;
if($(evt.target).closest('.content-box').length)
return;
if( $(".pulse-button").hasClass("pulse-button-active")){
$(".pulse-button").removeClass("pulse-button-active");
$(".pulse-button").next().addClass("context-closed");
};
});
$( "#tabs1,#tabs2" ).tabs();
});
What could I be doing wrong here?

You don't need the else in your .pulse-button click. Because the code in else block should be executed either any .pulse-button has class pulse-button-active or not. Change the your click event like following.
$(".pulse-button").click(function(e){
e.stopPropagation();
if($(".pulse-button").not(this).hasClass("pulse-button-active")) {
$(".pulse-button").not(this).removeClass("pulse-button-active");
$(".pulse-button").not(this).next().addClass("context-closed");
}
$(this).addClass("pulse-button-active");
$(this).next().removeClass("context-closed");
});
UPDATED PEN

Related

Jquery toggle div, allow clicking outside of div to close, also allow everything inside the div clickable

I have a toggle event on a div, and I've seen many questions regarding mine but nothing seems to work for what I'm trying to do, it either makes my div disappear in a few seconds, or it just doesn't work. Here's my jsfiddle.
I have a div that needs to toggle when another <div> is clicked. The toggled div has inputs in it that need to be filled out, and a submit button inside it as well. So I need clicks inside the div to be allowed, but only inside my div. So I want the div to show unless the user clicks outside of this div.
I'm using this query which toggles fine:
$('#MyDiv').click(function (event) {
$("#ToggledDiv").slideToggle();
});
And then this coding to hide it when clicked outside of the div which doesn't work:
$(window).click(function () {
$("ToggledDiv").hide();
});
I've tried solutions with e.preventDefault(); but that doesn't work, or $(document).click, even mousedown but it just doesn't flow how I want, it'll hide it within a few seconds, or it will prevent the toggle from even working so I'm lost.
The reason behind this behavior is Event Bubbling and Capturing of HTML DOM API. You can use event.stopPropagation() OR event.cancelBubble = true to prevents the event from bubbling up to the DOM tree, preventing any parent handlers from being notified of the event.
Another good article: events order
$('#MyDiv').click(function(event) {
$("#ToggledDiv").show();
disabledEventPropagation(event);
//console.log('2nd event');
});
$('#ToggledDiv').click(function(event) {
disabledEventPropagation(event);
//console.log('3rd event');
});
$(document).click(function() {
$("#ToggledDiv").hide();
//console.log('1st event');
});
function disabledEventPropagation(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (window.event) {
window.event.cancelBubble = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MyDiv" style="background-color:yellow">
click me to open
</div>
<div id="ToggledDiv" style="display: none;background-color:yellow">
<input type="text" />
<input type="submit" />
</div>
Take a look at the event when you click inside the #targetDiv. There are two properties you can use to evaluate what action to perform: event.target and event.currentTarget. In this case:
$('#ToggledDiv').on('click', function(event) {
console.log(event.target, event.currentTarget);
});
This is a good way to see if what clicked is actual target or a child element in the target.
To add to Chris' answer, you can see here that I check that the e.target is not inside the form using vanilla Node.contains, and also not the button...
https://jsfiddle.net/jmLdp45s/3/
var $button = $('button');
var $form = $('form');
$button.click(function() {
$form.slideToggle();
});
$(window).click(function(event) {
if (
!$form.get(0).contains( event.target ) // target is not inside form
&& event.target !== $button.get(0) // target is not button
) $form.hide();
});

Multiple Toggle. / Hide Show / Close others while open

Still a noob when it comes to this part of programming. I have a question regarading something I "solved" with the toggle function. I have 3 buttons ( placed in different divs on the page, so it's not a tab toggle ). What I try to achieve is when I have a button active and I click on another one, I want the active one to be closed. I looked up some jfiddle posts here with something similar, tried to implement it to the page and figure it out myself but nothing worked for me so far. The function I currently use for one button is
<script type="text/javascript">
$(function() {
$('#toggle5').click(function() {
$('.infotext').fadeToggle('fast');
return false;
});
});
</script>
It works just fine for one button to close and open it, but I have no idea where to start when I want two more buttons and let them interact with each other as mentioned before. Anybody has an idea how to do that ? And is the toggle function even the right function here ? I'd like to thank in advance for what ever answer I get here, great community.
Here is a good fiddle.
$("a").click(function(e) {
var tClass = $(this).attr("id"),
content = $("div.content." + tClass),
link = $(this);
$("div.content:not('." + tClass + "')").fadeOut("fast");
$("a").not(link).text("Open");
content.fadeToggle("fast", function() {
link.hide().text((content.is(":visible") ? "Close" : "Open")).fadeIn("fast");
});
e.preventDefault();
});​
If by closed you mean disabled then the code block bellow will do the trick.
Also, this will work only if your buttons are submit or button type.
<script type="text/javascript">
$(function() {
// click event for the #toggle5 button
$('#toggle5').click(function() {
// check if the #toggle6 is disabled
if ( !$('#toggle6').is(':disabled')) {
// if is not disabled, then disabled it
$('#toggle6').attr("disabled", "disabled");
}
return false;
});
});
</script>
If your buttons are links you will need to fire the preventDefault event
Docs here: http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29
<script type="text/javascript">
$(function() {
// click event for the #toggle5 button
$('#toggle5').click(function() {
$('#toggle6').on("click",function(e){
// check if we hire the preventDefault event already
if(!e.isDefaultPrevented()
e.preventDefault();
});
return false;
});
});
</script>
This will allow multiple toggle elements. Click toggle first one to open. Click to open the second one and it will close the first one and then open the 2nd one. So forth and so on. Can also close toggles with a click without having to open another one.
The HTML Markup
<div class="toggle">See Stuff</div>
<div class="paragraph">
<p>Content</p>
<p>Content</p>
<p>Video</p>
<p>Image</p>
</div>
The jQuery
<script>
$('.paragraph').hide();
$('.toggle').click(function() {
var panel = $(this).next()
$('.paragraph').not(panel).slideUp();
panel.slideToggle({
direction: "down"
}, 1000);
});
</script>

Close Toggle on outside click

I'm still quite new to javascript and JQuery...How do I get this div to close by clicking outside the toggle area (I don't want the user to have to use a close button)
the code looks like this:
function toggleDiv(divId) {
$("#"+divId).toggle();
}
function showonlyone(thechosenone) {
$('.newnote').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(0);
}
else {
$(this).hide(0);
}
});
}
and the html looks like this
<div class="note">
<a id="myHeader1" href="javascript:showonlyone('newnote1');" >
<img src="images/SN_NotesPage_14.png">
</a>
<div class="newnote" id="newnote1">
<a>
<img src="images/SN_NotesPage_16.png">
</a>
</div>
</div>
thank you
What I usually do is adding a click event listener to the document body which closes the overlay. To prevent closing the overlay by clicking on it I add a second click event listener to the overlay which contains ev.stopPropagation();
So with jQuery it would look like:
$(document.body).bind('click.closeNote', function() {
$('.newnote').hide();
});
$('.newnote').bind('click.closeNote', function(ev) {
ev.stopPropagation();
});
Another way is to add a transparent div (with a lower zIndex than the note) which covers the whole page. You could then add a click event listener to this div which closes the note.
Edit:
Please note, that the example above is not very performant as it executes a selector on every click. Just bind this event when a note is shown and unbind it when they get closed.

Jquery - hide on click anywhere on document

I have a div that hides whenever you click outside of it but I'm having some trouble getting certain links inside the div to work (and not hide the div).
$(document).click(function() {
fav.hide();
});
theDiv.click(function(e) {
e.stopPropagation();
});
That is what I have for the whole clicking outside and closing event. Heres the thing: I have two types of links in my div, one regular link and another which is a javascript one. The regular one redirects OK but the javascript one doesn't do anything.
Could somebody help me out? Thanks.
EDIT:
Here are the bits of my code that might help out
var fav = $('#favorites');
// Open & close button
$('#favorites_a').click(function(e) {
e.stopPropagation();
e.preventDefault();
fav.toggle();
});
$('a.c',fav).live('click', function(e) {
alert('hey');
});
$(document).click(function() {
fav.hide();
});
fav.click(function(e) {
e.stopPropagation();
});
HTML (built after page load):
<div id="favorites">
<div class="wrap">
<ul><li>AB</li></ul>
</div>
</div>
This could be a problem with the live() click event handler. When you use live the event handler is actually attached to the document. So the event needs to bubble up to the document, but your click event handler on fav prevents bubbling up.
It works with delegate though:
fav.delegate('a.c', 'click', function(e) {
alert('hey');
});
Here, the event handler is added to fav.
DEMO
I think your code for fav is preventing the 'B' link from working. Instead of .live(), try:
$('a.c').click(function() { ... });
instead.

how to make the menu close if it is clicked out

i have an menu with some values and i got someting hidden and while click on more button it shows like google more menu... if it is clicked out it is not hiding till the more menu is clicked once again
More<small>▼</small><div class="more list" id="one" style="display:none">test <span style="color:#329">|</span> test1 <span style="color:#169">|</span> test4</div></div>
Script:
function toggle(one)
{
var o=document.getElementById(one);
o.style.display=(o.style.display=='none')?'block':'none';
}
how to make it close while the mosuse clicks on any other place other than the menus
Try using the onblur event.
I see you've tagged this with jQuery, if that is an option, you can clear up the link a bit, like this:
More<small>▼</small>
And use unobtrusive script combined with event bubbling to your advantage, like this:
$(function() {
$(".more_link").click(function(e) {
$(this).next(".more").toggle();
e.stopPropagation();
});​​
$(".more").click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$(".more").hide();
});​
});
You can test it out here, this only closes the menu if you clicked neither the menu of the toggle, e.g. clicking one of the test links will not close it. If you want it to, just remove the $(".more").click(function(e) { e.stopPropagation(); }); portion.
It uses event.stopPropagation() to stop the click from bubbling up to document, which if happens (and would if you clicked anything else) triggers its click handler, closing all the .more elements.
I wouldn't use onBlur because it's not a good accessibility approach (for example if the user is using tab to navigate the page).
Look at this solution instead:
jQuery click event for document but ignore a div
Typically, I let the event bubble up to the 'body' or 'html' doc and check if the target is what i want (and/or isn't contained within what i want). If the event target is not contained within your menu, then perform your desired operation (in this case, hide the div).
i.e.
jQuery(document).ready(function(){
jQuery("html").bind("click", function(evt){
var $target = jQuery(evt.target);
var shouldShowMenu = $target.hasClass("menu_toggle");
shouldShowMenu |= $target.parents(".menu_toggle, .more_list").length;
if(!shouldShowMenu)jQuery(".more_list").hide();
});
});
NOTE: your markup would needs to be extended such that the "more" href becomes has a class attribute, class="menu_toggle"

Categories