my javascript prevent my code from working - javascript

I have made a side nav bar on toggled and by clicking on any point away from the navbar buttons navbar collapse and buttons not working on clicking on it
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
$(document).click(function (e) {
if ($('#wrapper').hasClass('toggled')) {
$("#body").click(function (e) {
e.preventDefault();
$("#wrapper").removeClass("toggled");
});
}
});

Don't bind a click event after a click event.
I don't see the use of the $(document).click(function(e){ })
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
$("#body").click(function (e) {
e.preventDefault();
if ($('#wrapper').hasClass('toggled'))
$("#wrapper").removeClass("toggled");
});
And maybe remove the # on the $('#body') if it needs to be on the <body> tag and the <body> tag has no id. Because the # is an id selector.

Actually you are overriding the click event handler on your $("#menu-toggle") element, you defined in:
$("#menu-toggle").click(function (e) {
By attaching a click event to the document in line:
$(document).click(function (e) {
Because document is the global element in the page and all other elements are inside of it, so by attaching a click event handler to the document you are omitting all other click handlers on the page.
Edit:
Another issue in your code is that you are attaching a click event handler inside another click event handler:
$(document).click(function (e) {
if ($('#wrapper').hasClass('toggled')) {
$("#body").click(function (e) {
e.preventDefault();
$("#wrapper").removeClass("toggled");
});
}
});
This will attach the second handler, to the body element, each time the document is clicked, which is a very wrong approach because you are always attaching a new click event handler on click of document which will lead to bad performance in your appplication.

Related

How to know html element is triggered or not

I'm able trigger mouseup and mousedown events. For triggering I'm using:
$(document).ready(function(){
$("html").mouseup(function(){
console.log("mouseup");
});
$("html").mousedown(function(){
console.log("mousedown");
});
});
My issue is, If I'm clicking on white space also my code was triggering. So, I want to trigger while user clicks on HTML elements only not on white screen. Is there any possibility to do this?
I was checking you question and realize that you want something generalized. So what I have done is, I have added a condition in which if the target is html, your further code will not execute(only event will be called).
$("html").mouseup(function(event){
if(event.target !== $('html')[0]){
console.log("mouseup");
}
});
$("html").mousedown(function(event){
if(event.target !== $('html')[0]){
console.log("mousedown");
}
});
Write now you adding the events on the whole html div. This means everything wrapped within <html> ... </html> tags will respond to that event. Fix it to the name of the tag of the particular div you want to respond to the event.
For Example for a button it will become
$('button').on('mouseup', () => {
console.log('mouse up on button')
})`
You can use * selector for it.
$(document).ready(function() {
//$("html").find("*").mouseup(function(e) { or
$("html *").mouseup(function(e) {
console.log("mouseup");
e.stopPropagation();
});
//$("html").find("*").mousedown(function(e) { or
$("html *").mousedown(function(e) {
console.log("mousedown");
e.stopPropagation();
});
});

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
}
});

Prevent click on outer li while clicking on inner link

I have some lis including a links as below
<li>
<span>SomeText</span>
<a href='someurl' class='entityDetailModal'>sometext</a>
</li>
I am using a third party library ('LightGallery') that adds click event on Li, and by Jquery I have add click event to the links to show a dialog.
The problem is when I click on link both click event will be fired,
my click event handler is
$('body').on("click", 'a.entityDetailModal', function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
I tried event.stopPropagation() and event.preventDefault(); and return false; in link onclick event handler but they don't work.
Sample:http://jsfiddle.net/HuKab/30/
How can I overcome this?
Update
It seems the problem is the way I add click event handler,
using this way it seems that everything is ok
$('a.entityDetailModal').click(function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
Update 2
Thanks #Huangism, this post stackoverflow.com/questions/16492254/pros-and-cons-of-using-e-stoppropagation-to-prevent-event-bubbling is explaining the reason.
Use stopPropagation(); in child element
$("li").click(function (e) {
alert("li");
});
$("a").click(function (e) {
e.preventDefault(); // stop the default action if u need
e.stopPropagation();
alert("a");
});
DEMO
It is not very clear to me what your problem really is. If you simply want to get rid of the click on the li tag you may use .unbind() from jQuery (see: http://api.jquery.com/unbind/). You should end up with only your click event.
Another thing that might help is to use something like:
$("a").on('click.myContext', function(event) {
//Your action goes here
}
This way you can have parallel events and turn them on with $("a").on('click.myContext') and off with $("a").off('click.myContext')
Edit: Use:
$("a").on('click.myContext',function (e) {
e.stopPropagation();
alert("a");
});
see working example: http://jsfiddle.net/bGBLz/4/

jQuery click event triggered multiple times off one click

I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on Stack Overflow to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.
The jQuery, triggered on document.ready
function setupHorzNav(portalWidth) {
$('.next, .prev').each(function() {
$(this).click(function(e) {
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
});
function initiateScroll(target) {
var position = $(target).offset();
$('html, body').animate({
scrollLeft: position.left
}, 500);
}
}
Example HTML
<nav class="prev-next">
Prev
Next
</nav>
In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.
Have I written the code wrongly or is there a bug?
-- Some extra info ------------------------------------------
setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.
if ( portalWidth >= 1248 ) {
wrapperWidth = newWidth * 4;
setupHorzNav(newWidth);
}
else
{
wrapperWidth = '100%';
}
There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.
<nav class="prev-next">
Prev
</nav>
Try unbinding the click event like this
$(this).unbind('click').click(function (e) {
});
You don't need .each() for binding event handlers. Try this instead:
$('.next, .prev').click(function(e){
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
EDIT:
I think it is the way you are attaching the event handler from within the setupHorzNav function that is causing it. Change it to attach it only once from say, $(document).ready() or something.
I have managed to get the situation of multiple event handlers by attaching the event handlers from a function that gets called from event handler. The effect is that the number of click event handlers keeps increasing geometrically with each click.
This is the code: (and the jsfiddle demo)
function setupNav() {
$('.next, .prev').each(function () {
$(this).click(function (e) {
setupNav();
var target = $(this).attr('href');
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
});
}
setupNav();
See how calling the setupNav() function from the click event handler adds multiple eventhandlers (and the click log message) on successive clicks
Since it is not clear from your question whether you are calling the binding function multiple times, a quick and dirty fix would be:
$('.next, .prev').unbind('click').click(function() {
...
});
What you are doing here is unbinding any previously bound event handlers for click and binding afresh.
Are there no other click bindings elsewhere?
Are you loading the page with ajax?
You could also try this:
$('.next, .prev').click(function (e) {
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});

JavaScript + addEventListener 'click' ignored on select html object

I've added an eventListener on the document in hopes to hide myWidget whenever anything within the document is clicked (except for the widget of course).
myWidget.addEventListener('click', function (e) {
e.stopPropagation();
}, false);
document.addEventListener('click', function (e) {
myWidget.style.display = 'none';
console.log(e.target);
});
Now this seems to work on everything but select html objects. Selecting a select box shows the select content, but the widget is not hidden and the console.log never fires. Any reason why?
I think you want the change event
document.addEventListener('change', function (e) {
myWidget.style.display = 'none';
console.log(e.target);
});

Categories

Resources