automatic close function for selection - javascript

I have a button which creates a pulldown in which you can select several categories.
Now i want this to close automatically when i click outside the pulldown.
Something like a lightbox or modal popup which closes if you click anywhere else on the page.
Now i have to click the button again to close it. If i dont and go elsewhere on the page, the dropdown stays visible (until i click it)
This is the code of the button:
$(function(){
$('#browse-btn').click(function(){
$('#browse-content').toggle('1000');
$(this).toggleClass('active');
if ($(this).hasClass('active')) $(this).find('span').html('▲')
else $(this).find('span').html('▼')
});
$(".scroll-top").scrollToTop();
$("#category_id").selectbox();
});
Is this possible?
thanks

Using jquery this is the code I used for a similar case scenario sometime ago:
$(document).click(function(event) {
if(!$(event.target).closest('.pulldown').length) {
if($('.pulldown').is(":visible")) {
$('.pulldown').slideUp()
}
}
})
You can read more about this in the original post How to detect a click outside an element? submitted by Art.

I'm not exactly sure of the elements you want to hide as you don't have a demo, so I cannot provide a fully working code, however you should do something like this:
$("body").click(function(event) {
if (event.target.id != "browse-btn") {
// Do something when there's a click outside of #browse-btn
// and the element you want to hide is currently visible
}
});

You can attach a click event to all chidren of the body tag that removes that active class, but you would want to make sure to unbind that event so it doesn't run every time a click takes place that doesn't have some sort of prevent default on it. Something like this:
$(function(){
var hidePulldown = function(){
$('#browse-btn').removeClass('active');
$('body *').unbind("click", hidePulldown);
}
$('#browse-btn').click(function(){
$('#browse-content').toggle('1000');
$(this).toggleClass('active');
if ($(this).hasClass('active')) $(this).find('span').html('▲')
else {
$(this).find('span').html('▼');
$(document).on('click', 'body *', hidePulldown);
}
});
$(".scroll-top").scrollToTop();
$("#category_id").selectbox();
});
Also, the
$(document).on('click', element, function(){function body})
is the preferred way to attach click events i believe: $(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

This is what worked flawlessly for me after reading some of the answers here:
$(document).click(function(event) {
if(!$(event.target).closest('#menucontainer').length &&
!$(event.target).is('#menucontainer')) {
if($('#menucontainer').is(":visible")) {
$('#menucontainer').hide();
}
}
})
Thanks for pointing me in the right way!

Related

Checking button click event and doing something and removing them if user clicks elsewhere

I am attaching a onclick function to the button#1 and according to this function i am changing other buttons' opacity and disabling user to click on them.
But I want to undo what has been changed onclick event, making other buttons as normal.
My javascript and jquery code as below;
btnLink.onclick = function(e) {
var divToShow = document.getElementById('linkNewDiv');
console.log('clicked');
divToShow.style.display = 'inherit';
$(btnVideo).prop('disabled',true);
$(btnVideo).addClass('opacityReducing');
$(btnPicture).addClass('opacityReducing');
$(btnPublish).addClass('opacityReducing');
$(btnPicture).prop('disabled',true);
$(btnPublish).prop('disabled',true);
$(btnCheck).addClass('opacityReducing');
}
I couldnt manage to figure it. I found a one way if user clicks outside of the elements I am changing elements style and disable property by writing all these codes again. Any better solutions ? Thanks :)
You can achieve this with stopPropagation(). I made some changes to your code to make it more readable, check this:
$(document).on('click', function(e) {
console.log('clicked');
$('#linkNewDiv').css("display", "inherit");
$(btnVideo, btnPicture, btnPublish).removeClass('opacityReducing').prop('disabled', false);
$(btnCheck).removeClass('opacityReducing');
});
$('#bnLink').on('click', function(e) {
e.stopPropagation();
console.log('clicked');
$('#linkNewDiv').css("display", "inherit");
$(btnVideo, btnPicture, btnPublish).addClass('opacityReducing').prop('disabled', true);
$(btnCheck).addClass('opacityReducing');
});

jQuery if body hasClass then sidemenu toggleClass issue

What I'm trying to achieve is toggling the sidemenu on click anywhere in the body except inside sidemenu div itself. I currently can toggle the sidemenu from its toggle link (comment out line 13-14 in js fiddle) but not by clicking anywhere on body. This is the concerned code:
$('body').bind('click', function (e) {
var opened = $('body').hasClass('sidemenu-open');
if (opened === true) {
$('.sidemenu').removeClass('is-visible');
$('body').removeClass('sidemenu-open');
}
});
JSFIDDLE
I know I can add a wrapper for the content but I don't have much flexibility in the HTML structure.
There are two problems. First, when you click on the link, the click is bubbling out to the body. So the menu toggles open, then it toggles closed again, so nothing happens. Use event.stopPropagation() to prevent that.
Second, when the side menu is closed, <body> is just the one line containing the link. If you want to be able to click anywhere in the window, use $(document) rather than $('body').
$(function () {
$('.sidemenu-toggle').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('.sidemenu').toggleClass('is-visible');
$('body.sidemenu-enabled').toggleClass('sidemenu-open');
$('.sidemenu').toggleClass('sidemenu-open');
});
});
$(document).on('click', function (e) {
var opened = $('body').hasClass('sidemenu-open');
if (opened === true) {
$('.sidemenu').removeClass('is-visible');
$('body').removeClass('sidemenu-open');
}
});
DEMO
Your click on the side menu is propagating down to the body and activating that handler as well - preventDefault isn't what you're after, you need to return false as well. Try this click handler instead.
$(function () {
$('.sidemenu-toggle').on('click', function (event) {
$('.sidemenu').toggleClass('is-visible');
$('body.sidemenu-enabled').toggleClass('sidemenu-open');
$('.sidemenu').toggleClass('sidemenu-open');
return false;
});
});
You can get the target element in click event by which you can have further conditions.
$('body').click(function(evt){
if(evt.target.id == "your_sidemenu_id"){
//do nothing
}
else{
//do the toggle here as this will be implemented whenever any element is clicked other than your sidemenu
}
});

mouseleave/enter bind/unbind logic

I'm trying to build a simple script for a form. The script will show the form when the user hovers over the container div. Then I want to check to see if the user clicks on any form input, if not the form will hide. If an input or textarea are in focus I unbind mouseleave. If the user want's to close the form at this point he needs to click on a close button.
The problem I have right now is that after I have an input in focus and I close the form, on the next hover the form doesn't hide. I have to click the close button again. How do I 'reset' or disable the mouseleave unbind when the user clicks on close?
This is the relevant part of the script:
$(".close").on('click', function() {
$(".background").removeClass("green");
$(".q-form").hide();
$('.close').hide();
});
$(".container-background").on('mouseenter', function(){
$('.q-form').show();
$('.close').show();
$('.background').addClass("green");
});
$(".container-background").on('mouseleave', function() {
f ($('#contactForm input').is(':focus')) {
$(".container-background").off("mouseleave");
} else {
$('.q-form').hide();
$('.close').hide();
$('.background').removeClass("green");
}
});
First, a little offtopic: I recommend against checking for an input in :focus. A better approach for the scenario you described is to have:
$(document).on("focus", "#contactForm input", function() {
$(".container-background").off("mouseleave");
});
As for the problem you have with unbinding the event handler, you can just reattach it on form close:
$(".container-background").on("mouseleave", myFunction);
$(".close").on('click', function() {
$(".background").removeClass("green");
$(".q-form").hide();
$('.close').hide();
$(".container-background").off("mouseleave", myFunction)
.on("mouseleave", myFunction);
});
var myFunction = function() {
// You won't need this condition if you also do what's above
if (!$('#contactForm input').is(':focus')) {
$('.q-form').hide();
$('.close').hide();
$('.background').removeClass("green");
}
};
On second thought you can also just do this, and not have the .off() call at all:
if (!$('#contactForm input').is(':focus')) {
Personally, I don't like to use .hover or .on. I use .mouseenter and .mouseleave. Then, if you just create a .mouseenter, there would be no code to put it back into the unfocused state. Here is an example:
$("#something").mouseenter(function(){
$(this).animate({
//some css or whatever.
})
})
as long as you don't put a .mouseleave, it should not unfocus.

Click anywhere in the page to close div

I have an overlay div that fades in when I click on a DOM element. I would like to be able to close it when I click anywhere on the page ( except the div itself) but it does not work..
Here is my code:
//Script for showing the DIV called overlay.
<script>
$(function() {
$('#loginfooter').click(function(){
$('#overlay').fadeIn(200,function(){
$('#box').animate({'top':'20px'},'slow');
});
return false;
});
$('#boxclose').click(function(){
$('#box').animate({'top':'-800px'},500,function(){
$('#overlay').fadeOut('fast');
});
});
});
</script>
//Script for hiding the div after clicking anywhere..
<script>
$(document).ready(function(){
$('#overlay').on('click',function(ev){
var myID = ev.target.id;
if(myID!=='overlay'){
$('#box').animate({'top':'-800px'},500,function(){
$('#overlay').fadeOut('fast');
});
}
});
});
</script>
Just replace this:
$('#overlay').on('click', function (ev) {
with this
$(document).on('click', function (ev) {
and try again....
Actually, when you are clicking on the overlay element, the myID variable value is always == 'overlay'. Hence, it never goes inside the if statement.
DEMO 1
$(document).on('click',function(e){
if(!$(e.target).closest('#overlay').length)
$('#overlay').hide();
});
Other possibility without using any delegate event:
DEMO 2
$('#overlay').on('blur', function (e) {
$(this).hide();
});
Even you'll see most people using the first method, using the second one will avoid to have to use any delegate event which is better IMO. You just have to set focus on overlay when open it or when added to DOM, depending your specific case.
Would this work for you: jsfiddle?
I changed this:
if(myID!=='overlay'){
to this
if(myID=='overlay'){
so that you target the overlay instead of the box.

How do I write 'if not clicked' or 'if clicked outside element', using Jquery?

I'm kind of stuck on a problem of how to stop my menu from executing the fadeOut() function. When I click the main links on my menu to open the submenu it just fades out. Here is how the code looks at the moment:
$('a.main-menu-item').click(function(){
if($('.rtmenu:visible')){
$('.rtmenu').click(function(e) { e.stopPropagation(); });
$(document).click(function() {
$('.rtmenu').fadeOut(200);
});
}
})
Can anyone tell me how I can write 'if not clicked a.main-menu-item' where it says 'document'?
Much Appreciated
SOLUTION FOUND!
$('.rtmenu').click(function(e) { e.stopPropagation(); });
$('.rtmenu').mouseout(function(){
$(document).one('click',function() { $('.rtmenu').fadeOut(200); });
})
Have a look at Ben Alman's "outside events" plugin. It allows you to define a range of events, not just click events. With it, your code would look something like this:
$('.rtmenu').bind('clickoutside', function() {
$(this).fadeOut(200);
});
As an aside, you shouldn't set up the bind inside the click event for the menu, this will attach another handler every time the menu option is clicked. Your code should be replace with something like:
$('a.main-menu-item').click(function(){
// Show menu item
});
$('.rtmenu').bind('clickoutside', function() {
$(this).fadeOut(200);
});
use blur event to handle losing focus.
This might help also.

Categories

Resources