How can i unbind for specific jquery scroll event? - javascript

I am having scroll event.
this.todayScrollerRef = $(window).scroll(() => {
console.log('some stuff');
});
On button click i want to unbind from the event
So when i try
$(window).unbind('scroll');
it works - and i don't get some stuff in console when i am scrolling after the button click.
But because i have another window.scroll event i don't want to use $(window).unbind('scroll');
because it unbinds all of the scroll events.
So i want to unbind specific one - and when i try
$(window).unbind('scroll', this.todayScrollerRef);
for my created todayScrollerRef reference - it does not work.
Scroll event is not destroyed
I also tried with
$(window).on('scroll', this.todayScroller.bind(this));
todayScroller() {
console.log('some stuff');
}
// on btn click
$(window).off('scroll', this.todayScroller.bind(this));
and it still does not work.
Where is my mistake ?

Have your handler like this:
this.todayScrollerRef = function() {
console.log('sd');
};
to Bind
$( window).bind( "scroll", this.todayScrollerRef );
to unbind:
$(window).unbind( "scroll", this.todayScrollerRef );

Related

jQuery on scroll listener after click event

What is the proper way to activate an on scroll listener after a click event?
I'm currently using:
$('.button').click(function (event) {
$(window).on("scroll", someFunction);
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
}
On a click event I enable the scroll listener which runs someFunction. The function does stuff and disables the scroll listener when finished. The scroll listener is enabled again on click.
My concern is that I'm not doing it right. Please advise!
Note: The scroll listener cannot run indefinitely. It starts on click and must finish at the end of myFunction.
Note: I'm not trying to detect when user stops scrolling..
You could use jQuery .one():
$('.button').on('click', function() {
$(window).one('scroll', someFunction);
});
Every single click adds an additional scroll event listener. I would encapsulate the binding with an additional variable:
var isScrollBindingActive = false;
$('.button').click(function (event) {
if (!isScrollBindingActive) {
isScrollBindingActive = true;
$(window).on("scroll", someFunction);
}
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
isScrollBindingActive = false; // allow binding again if wished
}
You can do it the following way:
$('.button').click(function (event) {
$(window).bind("scroll", someFunction);
}
someFunction = function() {
//do stuff
$(window).unbind("scroll"); // remove scroll listener
}

Using :not() to ignore clicks on children links?

In a script I'm writing with JQuery I'm trying to add a click handler to a div, but ignoring clicks on the children a tags inside it.
You can see a JSFiddle of how I'm currently trying (and failing) to make it happen here: http://jsfiddle.net/q15s25Lx/1/
$(document).ready(function() {
$(document).on('click', '.post:not(a)', function(e) {
alert($(this).text());
});
});
<div class="post">This is some text in a div. Click me please.</div>
In my real page, the a tags all have their own click handlers, so I need to be able to listen for those concurrently.
So, ideally I'd like to use something like the :not() selector to ignore clicks on this particular handler.
Is something like this possible?
You'll need to add another handler that acts on the anchor and stops the event from propagating:
$(document).on('click', '.post a', function (e) {
e.stopPropagation();
e.preventDefault();
});
Without this, when you click the a the event bubbles up to the parent .post, and the handler fires on that anyway.
You need to stop event propagation to child elements using .stopPropagation():
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
});
Working Demo
Just return false; in the end of event handler.
$(document).on('click', '.post', function (e) {
alert($(this).text());//will show entire text
});
$(document).on('click', '.post a', function (e) {
alert($(this).text());//will show 'text'
return false;
});
working fiddle: http://jsfiddle.net/q15s25Lx/2/
return false will server as both e.preventDefault() &
e.stopPropagation()
Try to stop the event from bubbling up the DOM tree using stopPropogation()
$(document).ready(function() {
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
alert($(this).text());
});
});
Fiddle Demo
All of the other posts did not explain why your code failed. Your selector is saying : Find an element that has the class post and is not an anchor. It is NOT saying if a child was clicked and was an achor do not process.
Now there are two ways to solve it. One is to prevent the click from bubbling up from the anchors. You would add another listener on the anchors.
$(document).on('click', '.post a', function (evt) {
evt.stopPropagation(); //event will not travel up to the parent
});
$(document).on('click', '.post', function (evt) {
console.log("Click click");
});
Or the other option is not to add a second event, but check what was clicked.
$(document).on('click', '.post', function (evt) {
var target = $(evt.target); //get what was clicked on
if (target.is("a")) { //check to see if it is an anchor
return; // I am an anchor so I am exiting early
}
console.log("Click click");
});
Or jsut let jquery handle it all for you. return false
$(document).on('click', '.post:not(a)', function() {
alert($(this).text());
return false;
});

Responsive Jquery toggle command

I am having an issue with my code. Whenever, I load up the page in the browser or in a mobile device, and I try to toggle it suddenly toggles multiple times when I just clicked on it once. I am trying to use this syntax code to make it responsive.
My CodePen
$(window).resize(function() {
$(".textcontent").hide();
if ($(window).width() <= 480) {
jQuery(function($) {
$(document).ready(function() {
$(".textcontent").hide();
$(".titleheader").click(function() {
$(this).toggleClass("active").next().slideToggle("fast");
return false;
});
});
});
}
});
The text toggles more than once because you are binding the click handler each time the resize event fires. Each bind attaches another handler so, depending on how many times the resize event fires, you might end up with many click handlers firing at once.
I suggest that you bind or unbind your click handler depending on the screen width, like so:
$(function() {
// function to toggle a text section
function toggleText(elm) {
$(elm).toggleClass("active").next().slideToggle("fast");
}
// resize event handler
$(window).on('resize', function() {
if ($(window).width() <= 480) {
// if window <= 480, unbind and rebind click handlers, and hide all text content
$(".titleheader").off('click').on('click', function() {
toggleText(this);
});
$(".textcontent").hide();
} else {
// if the window > 480, unbind click handlers and hide all text
$(".titleheader").off('click');
$(".textcontent").show();
}
}).trigger('resize'); // initialize - trigger the resize once upon load
});
WORKING EXAMPLE
You might also want to throttle or "debounce" your resize handler so it won't fire continuously in IE, Safari, and Chrome.
EDIT:
An alternate method is to set a flag to indicate whether the layout is "small" or "large". Then, only change the layout if the flag does not indicate the desired layout:
$(function() {
// layout flag (defaults to "not small")
var small = false;
// function to toggle a text section
function toggleText(elm) {
$(elm).toggleClass("active").next().slideToggle("fast");
}
// resize event handler
$(window).on('resize', function() {
if ($(window).width() <= 480) {
// if window <= 480 and the layout is "not small", bind click handlers and hide all text content
if (!small) {
console.log('made small');
$(".titleheader").on('click', function() {
toggleText(this);
});
$(".textcontent").hide();
// set the layout flag to "small"
small = true;
}
} else {
// if the window > 480 and the layout is "small", unbind click handlers and hide all text
if (small) {
console.log('made large');
$(".titleheader").off('click');
$(".textcontent").show();
// set the layout flag to "not small"
small = false;
}
}
}).trigger('resize'); // initialize - trigger the resize once upon load
});
WORKING EXAMPLE

how to target event for "shift keydown & click" on a div?

I want to control events when hovering a <div> element.
I have my code pretty much working, but I have 2 remaining problems!
When I first run the code in my JSFiddle, I need to click on the body of the document first to get the keydown to be recognised. If I run the code and hover right away and press shift nothing happens. I have it running on doc ready,so not sure why I need to click first? Anyway to get this to work right way without needing to click?
I trace out in the console the console.log('click and press'); This is getting fired each time I press shift and is not looking for a click - why is this getting fired when pressing shift when I call it within a function that says $(document).on('keydown click', function (e) {
DEMO
My JS code is as follows
$(document).ready(function () {
$(".target").hover(function () {
$(document).on('keydown click', function (e) {
if (e.shiftKey) {
// code to go here for click
console.log('click and press');
}
});
$(document).on('keydown', function (e) {
if (e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
$('.target').css('cursor', 'sw-resize', 'important');
});
});
});
Thanks
Your event binding is incorrect. you can use:
Demo: http://jsfiddle.net/g9ea8/8/
Code:
$(document).ready(function () {
var hovering = false;
$(".target").hover(function () {
hovering = true;
}, function() {
hovering = false;
});
$(document).on('click', function (e) {
if (hovering && e.shiftKey) {
// code to go here for click
console.log('hovering+shift+click');
}
});
$(document).on('keydown', function (e) {
if (hovering && e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
console.log('hovering+shift');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
if(hovering) {
$('.target').css('cursor', 'sw-resize', 'important');
console.log('hovering+keyup');
}
});
});
The reason why you need to click first on the fiddle demo is because the frame doesn't have focus, normally this should work fine.
You shouldn't be attaching a keydown listener, you only need a to attach click, otherwise keydown will fire the event regardless of a click occurring.
Also, currently you're attaching 3 handlers every time you hover over .target, see #techfoobar's answer for a cleaner solution.

.on event keeps getting fired over and over again

I'm trying to setup an event where it fires after my element is opened. So I have a tooltip and I have a click event which shows the tooltip. Then when that happens I setup a document click event that gets fired so if the user clicks anywhere on the stage it removes all tooltips. But what's happening is it gets called before the tooltip even gets a chance to show. So it's firing the document event over and over again.
$('.container img').popover({placement:'top', trigger:'manual', animation:true})
.click(function(evt){
evt.preventDefault();
el = $(this);
if(el.hasClass('active')){
el.popover('hide');
}else{
clearDocumentEvent();
el.popover('show');
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
hideAllTooltips();
});
}
el.toggleClass('active');
})
var hideAllTooltips = function(){
$('.container img').popover('hide');
$('.container img').removeClass('active');
}
var clearDocumentEvent = function(){
$(document).off('click.tooltip touchstart.tooltip');
};
The problem stems from event bubbling. You can verify this by doing the following test:
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
//hideAllTooltips();
console.log($(this)); // will return .container, body, html
});
Try using event.stopPropogation():
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(e){
e.stopPropagation();
hideAllTooltips();
});
DEMO:
http://jsfiddle.net/dirtyd77/uPHk6/8/
Side note:
I recommend removing .tooltip from the on function like
$(document).on('click touchstart', ':not(.container img)', function(){
e.stopPropagation();
hideAllTooltips();
});

Categories

Resources