Jquery If / Else statement stopping preventdefault - javascript

I have some code for a mega navigation and I need it to hover to drop the menu on desktop and click to the drop the menu on mobile.
Here is a snippet of code that I'm having problems with:
if( $('js-full-menu').hasClass('js-touch-menu') ) {
(function(megaNavTray){
menu.on('click', function(e){
e.preventDefault();
var wasOpen = megaNavTray.hasClass('is-active');
megaNavTrays.find('.js-mega-nav-tray').removeClass('is-active');
if(!wasOpen) {
megaNavTray.addClass('is-active');
megaNavTrays.addClass('is-active');
} else {
megaNavTrays.removeClass('is-active');
}
});
})(megaNavTray);
} else {
(function(megaNavTray){
menu.hoverIntent( function(){
megaNavTray.addClass('is-active');
megaNavTrays.addClass('is-active');
var wasOpen = megaNavTray.hasClass('is-active');
megaNavTrays.find('.js-mega-nav-tray').removeClass('is-active');
if(wasOpen) {
megaNavTray.addClass('is-active');
megaNavTrays.addClass('is-active');
} else {
megaNavTray.removeClass('is-active');
}
});
})(megaNavTray);
var fullNav = $('.js-full-menu');
fullNav.hoverIntent( function() {}, function() {
$('.js-mega-nav-tray').removeClass('is-active');
megaNavTrays.removeClass('is-active');
});
}
Basically the problem is that with the if else statement removed leaving only the following code, the preventdefault works fine. Using the full code above the links direct to their pages instead of dropping the meganav on click.
(function(megaNavTray){
menu.on('click', function(e){
e.preventDefault();
var wasOpen = megaNavTray.hasClass('is-active');
megaNavTrays.find('.js-mega-nav-tray').removeClass('is-active');
if(!wasOpen) {
megaNavTray.addClass('is-active');
megaNavTrays.addClass('is-active');
} else {
megaNavTrays.removeClass('is-active');
}
});
})(megaNavTray);
Any ideas why the if / else would be stopping the preventdefault from working?
Thanks in advance!

if( $('js-full-menu').hasClass('js-touch-menu') )
should be
if( $('.js-full-menu').hasClass('js-touch-menu') )
you forgot the . in the class selector.

I may be wrong, but try putting
function(event)
instead of
function(e)
Solved an issue for me in FF the other day.

Related

Exceute code only certain window size without relaoding the page jQuery or javascript

I'm trying to run this code when window size hit certain width.
This code is working on page load, i want it to run when user resize the browser window.
if ($(window).width() > 1023) {
$('.has-children').children('a').on('click', function(event){
if( !checkWindowWidth() ) event.preventDefault();
var selected = $(this);
if( selected.next('ul').hasClass('is-hidden') ) {
selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');
selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');
$('.insided-overlay').addClass('is-visible');
} else {
selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');
$('.insided-overlay').removeClass('is-visible');
}
});
}
Can anyone please help me with this how can i achieve this?
Thanks
try to write this script as below:
$('.has-children').children('a').on('click', function(event){
if($(window).width() > 1023) {
if( !checkWindowWidth() ) event.preventDefault();
var selected = $(this);
if( selected.next('ul').hasClass('is-hidden') ) {
selected.addClass('selected').next('ul').removeClass('is-hidden').end().parent('.has-children').parent('ul').addClass('moves-out');
selected.parent('.has-children').siblings('.has-children').children('ul').addClass('is-hidden').end().children('a').removeClass('selected');
$('.insided-overlay').addClass('is-visible');
} else {
selected.removeClass('selected').next('ul').addClass('is-hidden').end().parent('.has-children').parent('ul').removeClass('moves-out');
$('.insided-overlay').removeClass('is-visible');
}
}
});
I hope this will works fine for you.
Thank you...

Hide popover on body click only if already visible

Hiding a div (for example #popover) on click is easy:
$(document).ready(function() {
$("#trigger").click(function(e) {
$("#popover").toggle();
e.stopPropagation();
});
$(document).click(function(e) {
if (!$(e.target).is('#popover, #popover *')) {
$("#popover").hide();
}
});
});
But isn't this function fired every time the user uses a click? (Which does not make sense for me). Can I somehow limit this function to fire only if #popover is already visible?
In that case you can try using $(document).one(function(e) {...}); every time you show #example.
$(document).ready(function() {
var didBindToBody = false;
function closePopOverOnBodyClick() {
didBindToBody = true;
$(document).one('click', function(e) {
if (!$(e.target).is('#popover, #popover *')) {
$("#popover").hide();
}
else {
closePopOverOnBodyClick();
}
didBindToBody = false;
});
}
$("#trigger").click(function(e) {
$("#popover").toggle();
e.stopPropagation();
if (!didBindToBody && $("#popover").is(":visible")) {
closePopOverOnBodyClick();
}
});
closePopOverOnBodyClick();
});
DEMO
You could try something like
$(document).click(function(e) {
if (!$('#example').is(":visible")) {
return false;
} else if (!$(e.target).is('#popover, .login-panel *')) {
$("#popover").hide();
}
});
Or you could combine the two conditionals into one, just thought I'd keep it separate for readability and to make my suggestion easier to spot.

Reponsive Menu Js (clear dom?)

I want to create a responsive menu for my website, however, I have a problem : I have two devices (desktop & mpbile phone) with the same HTML but two different JS. I share my problem in few line of code.
eventDesktop = function() {
$('header').click(function() {
console.log('Desktop');
});
};
eventPhone = function() {
$('header').click(function() {
console.log('Phone');
});
};
eventWitch = function() {
if (window.innerWidth > 480) {
eventDesktop();
} else {
eventPhone();
}
};
eventWitch();
$(window).resize(function() {
eventWitch();
});
So, after loading that's ok because only one is load, but after resize there are 2 fonctions for the same element, and I want to have only witch one i need. So here, i want to see on the console only 'Desktop' or 'Phone' but not the 2 both, when i click.
Thanks for reading.
If you have question i can specify my ask.
Greet.
You are binding two events on same element on the resize of window. You could try this
$('header').click(function() {
if(window.innerWidth > 480)
console.log('Desktop');
else
console.log('Phone');
});
So, check everytime when user click on header.
It seems like you creating 2 different Event-Handlers, so he is using both in your case.
Try to .unbind() them:
$(window).resize(function() {
$( 'header' ).unbind( 'click' );
eventWitch();
});
So all Click events will be removed, keep that in mind.
There is another method I didn't tried, but maybe it helps: jQuery multiple click event
As andrea.spot wrote: "You need to make your handler function return false.. it prevents the event from bubbling."
Adding this to your code:
eventDesktop = function() {
$('header').click(function() {
console.log('Desktop');
return false;
});
};
eventPhone = function() {
$('header').click(function() {
console.log('Phone');
return false;
});
};
The last solution would be changing the way of thinking. This means do the Click-Handler and THAN check for the Windows Size. Currently you checking for the Window Size and than calling a Click-Handler, this will always lead to multible Click Handlers, but not if you create one handler and than do the statements.
My text to code:
eventWitch = function() {
$( 'header' ).click( function(){
if (window.innerWidth > 480) {
console.log( 'Desktop' );
} else {
console.log( 'Mobile' );
}
}
};
Does one of this solutions works for you?
try this
eventDesktop = function() {
$('header').unbind('click').click(function() {// here it will removes all old click events assigned to this element.
console.log('Desktop');
});
};
eventPhone = function() {
$('header').unbind('click').click(function() {// here it will removes all old click events assigned to this element.
console.log('Phone');
});
};
eventWitch = function() {
if (window.innerWidth > 480) {
eventDesktop();
} else {
eventPhone();
}
};
eventWitch();
$(window).resize(function() {
eventWitch();
});

JQuery trigger element itself in a bind

Can someone explain me why this snippet can't work ?
I can't use specific features like window.location, submit(), (instead of trigger()), because this function is bound to elements that are very differents.
$('a, button').bind('click', function(oEvent, oData) {
var oButton = $(this);
var bSkip = (oData && oData.skip);
if(true === bSkip) {
return true;
} else {
oEvent.preventDefault();
//oEvent.stopPropagation();
if(confirm('This is a confirm box')) {
$(oButton).trigger('click', { skip: true });
}
}
});
Thanks in advance ! ;)
In your case even though the click event gets fired the default behavior of the links may not be triggered because of the constraints imposed by the browser
If I understand what you are trying to do correctly(if the action s not confirmed then cancel the default behavior), then you can achieve it by the below... there is no need to fire the event again
$('a, button').bind('click', function (oEvent, oData) {
if (confirm('This is a confirm box')) {
return true;
} else {
oEvent.preventDefault();
}
});
Demo: Fiddle

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources