stop event after first time - javascript

i am firing an event when im at a special scrollposition with jquery.inview. it works by adding classes if an element is in the viewport. in my script im saying the following
var $BG = $('#BG')
$('#BG').bind('inview', function (event, visible)
{
if (visible == true) {
$(this).addClass("inview");
} else {
$(this).removeClass("inview");
}
});
if($BG.hasClass("inview")){
$('#diagonal').css('left',0)
$('#diagonal').css('top',0)
}
but it fires the .css events again and again, but i want them to fire only at the first time the #BG gets the "inview" class.
thanks ted

You can add some var who tells if it has been fired or not :
var $BG = $('#BG'), firedInView = false;
$BG.bind('inview', function (event, visible) {
if(!firedInView) {
firedInView = true; //set to true and it won't be fired
//do your stuff
}
});

You can unbind the event handler using jQuery unbind method or use one method to handle event at most once.
http://api.jquery.com/category/events/event-handler-attachment/

Try with .one() instead .bind():
$('#BG').one('inview',

I am going on the assumption that you would like to remove the styles on diagonal when #BG is out of view?
I'd split this into two listeners
//If bg does not have class inview, addClass if it is visible
$('body').on('inview', '#BG:not(.inview)', function (event, visible) {
if (visible == true) {
$(this).addClass("inview");
$('#diagonal').css({'left': 0, 'top': 0});
}
});
//If bg does has class inview, removeClass if it is invisible
$('body').on('inview', '#BG.inview', function (event, visible) {
if (visible == false) {
$(this).removeClass("inview");
$('#diagonal').css({'left': 'auto', 'top': 'auto'});
}
});

Related

bootstrap carousel hide controls on first and last

How can I hide the left control if the carousel is on the first item, and how can I hide the right control when the carousel is on the last item.
My code below hides the control successfully but on page load it is as if the carousel first item is in the middle and the user can either go all the way through via the left or right controls.
http://bootply.com/99354
thanks
Bootply link
$('#myCarousel').on('slid', '', checkitem); // on caroussel move
$('#myCarousel').on('slid.bs.carousel', '', checkitem); // on carousel move
$(document).ready(function(){ // on document ready
checkitem();
});
function checkitem() // check function
{
var $this = $('#myCarousel');
if($('.carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
$this.children('.right.carousel-control').show();
} else if($('.carousel-inner .item:last').hasClass('active')) {
$this.children('.left.carousel-control').show();
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
The below code is an updated version of TheLittlePig's code for Bootstrap 3 that works both for multiple carousels on the same page and for indicator actions. The explained code is here
checkitem = function() {
var $this;
$this = $("#slideshow");
if ($("#slideshow .carousel-inner .item:first").hasClass("active")) {
$this.children(".left").hide();
$this.children(".right").show();
} else if ($("#slideshow .carousel-inner .item:last").hasClass("active")) {
$this.children(".right").hide();
$this.children(".left").show();
} else {
$this.children(".carousel-control").show();
}
};
checkitem();
$("#slideshow").on("slid.bs.carousel", "", checkitem);
Augmenting #TheLittlePig, it needs to be slightly different if you're using Bootstrap 3 because the event to attach the callback to is different: slid.bs.carousel. Also, if you have multiple carousels on one page you'll need to pass a unique css id for the carousel into the event handler. Here is a modified version that I use on my Rails site:
<script>
//<![CDATA]
id = '#carousel-<%=id%>';
$(id).on('slid.bs.carousel', { id: id }, bs_carousel_slid);
$(document).ready(function(){ $(id).trigger('slid.bs.carousel'); });
//]]>
</script>
That is repeated for each carousel. The <%=id%> is a ruby expression that is replaced by a unique id for the given carousel. Tweak that bit for your needs according to the language of your choice.
The difference is that the carousel's id is passed into the event handler function as event data so that the event handler can operate on the correct carousel. I also changed the ready event so that it triggers the slid.bs.carousel event (instead of calling the function directly) so it passes the correct event data to the event handler for each carousel.
The event handler is a function called bs_carousel_slid that I define elsewhere (those on Rails - it's in a file in app/assets/javascripts). The function is shown below:
function bs_carousel_slid(event)
{
var id = event.data.id;
var $this = $(id);
if($(id + ' .carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
} else if($(id + ' .carousel-inner .item:last').hasClass('active')) {
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
IF YOU'RE USING BOOTSTRAP 3:
The event is 'slid.bs.carousel' not 'slid'
$('.carousel').carousel({
interval: false,
})
$(document).ready(function () { // on document ready
checkitem();
});
$('#myCarousel').on('slid.bs.carousel', checkitem);
function checkitem() // check function
{
var $this = $('#myCarousel');
if ($('.carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
} else if ($('.carousel-inner .item:last').hasClass('active')) {
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}

Mouse Wheel Event and Scroll Event conflicting with eachother

My Problem is this:
I have a MouseWheel Event (from plugin: https://github.com/brandonaaron/jquery-mousewheel) that triggers a function:
$(document).on('mousewheel', onMouseWheel);
function onMouseWheel(event,delta)
{ Code... }
I Also have a Scroll Event that triggers another function:
$(document).on('scroll', onScroll);
function onScroll()
{ Code... }
However when using the mouswheel, both events are triggered and so both functions run, which I don't want them to. They have to be separate since using the mousewheel and dragging the scrollbar should give separate results. The problem only occurs that way around ie. the mousewheel function is not triggered by dragging the scrollbar.
EDIT:
I've realized with a little help, that the problem occurs because I use ScrollLeft() inside my mousewheel function, which of course causes the scroll event.
I've tried to think of a solution but with no luck. Can anyone help? Thanks!
EDIT: More code:
$(document).on('scroll', onScroll );
function onScroll()
{
code...
}
$(document).on('mousewheel', onMouseWheel ) );
function onMouseWheel(event,delta)
{
event.preventDefault();
if(delta<0)
{
detectDown();
}
else if(delta>0)
{
detectUp();
}
return false;
}
$(document).on("keydown", onKeyDown);
function onKeyDown(e)
{
event.preventDefault();
if (e.keyCode == 37)
{
detectUp();
}
else if (e.keyCode == 39)
{
detectDown();
}
}
function detectUp()
{
$("html, body").animate({scrollLeft:(currentElement.prev().position().left - 100)}, 800, 'easeOutQuad');
currentElement = currentElement.prev();
}
function detectDown()
{
$("html, body").animate({scrollLeft:(currentElement.next().position().left - 100)}, 800, 'easeOutQuad');
}
Maybe this helps?
Add return false at the end of the onMouseWheel function.
function onMouseWheel(event, delta) {
// code
return false;
}
This will disable the default scroll action for the 'mousewheel' event, hence the 'scroll' event will not be triggered.
fiddle
I've come to the realization, that the best solution is to make a custom scrollbar. This way we can avoid calling the scrolling function and having the different types of scrolling interfering with one another.

Prevent click event after drag in jQuery

I have a draggable <div> with a click event and without any event for drag,
but after I drag <div> the click event is apply to <div>.
How can prevent of click event after drag?
$(function(){
$('div').bind('click', function(){
$(this).toggleClass('orange');
});
$('div').draggable();
});
http://jsfiddle.net/prince4prodigy/aG72R/
FIRST attach the draggable event, THEN the click event:
$(function(){
$('div').draggable();
$('div').click(function(){
$(this).toggleClass('orange');
});
});
Try it here:
http://jsfiddle.net/aG72R/55/
With an ES6 class (No jQuery)
To achieve this in javascript without the help of jQuery you can add and remove an event handler.
First create functions that will be added and removed form event listeners
flagged () {
this.isScrolled = true;
}
and this to stop all events on an event
preventClick (event) {
event.preventDefault();
event.stopImmediatePropagation();
}
Then add the flag when the mousedown and mousemove events are triggered one after the other.
element.addEventListener('mousedown', () => {
element.addEventListener('mousemove', flagged);
});
Remember to remove this on a mouse up so we don't get a huge stack of events repeated on this element.
element.addEventListener('mouseup', () => {
element.removeEventListener('mousemove', flagged);
});
Finally inside the mouseup event on our element we can use the flag logic to add and remove the click.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
e.target.addEventListener('click', preventClick);
} else {
e.target.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
In the above example above I am targeting the real target that is clicked, so if this were a slider I would be targeting the image and not the main gallery element. to target the main element just change the add/remove event listeners like this.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
element.addEventListener('click', preventClick);
} else {
element.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
Conclusion
By setting anonymous functions to const we don't have to bind them. Also this way they kind of have a "handle" allowing s to remove the specific function from the event instead of the entire set of functions on the event.
I made a solution with data and setTimeout. Maybe better than helper classes.
<div id="dragbox"></div>
and
$(function(){
$('#dragbox').bind('click', function(){
if($(this).data('dragging')) return;
$(this).toggleClass('orange');
});
$('#dragbox').draggable({
start: function(event, ui){
$(this).data('dragging', true);
},
stop: function(event, ui){
setTimeout(function(){
$(event.target).data('dragging', false);
}, 1);
}
});
});
Check the fiddle.
This should work:
$(function(){
$('div').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('div').click(function(event) {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
$(this).toggleClass('orange');
}
});
});
DEMO
You can do it without jQuery UI draggable. Just using common 'click' and 'dragstart' events:
$('div').on('dragstart', function (e) {
e.preventDefault();
$(this).data('dragging', true);
}).on('click', function (e) {
if ($(this).data('dragging')) {
e.preventDefault();
$(this).data('dragging', false);
}
});
You can just check for jQuery UI's ui-draggable-dragging class on the draggable. If it's there, don't continue the click event, else, do. jQuery UI handles the setting and removal of this class, so you don't have to. :)
Code:
$(function(){
$('div').bind('click', function(){
if( $(this).hasClass('ui-draggable-dragging') ) { return false; }
$(this).toggleClass('orange');
});
$('div').draggable();
});
With React
This code is for React users, checked the draggedRef when mouse up.
I didn`t use click event. The click event checked by the mouse up event.
const draggedRef = useRef(false);
...
<button
type="button"
onMouseDown={() => (draggedRef.current = false)}
onMouseMove={() => (draggedRef.current = true)}
onMouseUp={() => {
if (draggedRef.current) return;
setLayerOpened(!layerOpened);
}}
>
BTN
</button>
I had the same problem (tho with p5.js) and I solved it by having a global lastDraggedAt variable, which was updated when the drag event ran. In the click event, I just checked if the last drag was less than 0.1 seconds ago.
function mouseDragged() {
// other code
lastDraggedAt = Date.now();
}
function mouseClicked() {
if (Date.now() - lastDraggedAt < 100)
return; // its just firing due to a drag so ignore
// other code
}

Delay animation until other animation is complete (sliding content(

I have this code which animates between divs sliding out. If an item is clicked, it's relevant content slides out. If another item is clicked, the current content slides back in and the new content slides out.
However,
var lastClicked = null;
var animateClasses = ['ale', 'bramling', 'bullet', 'miami-weisse'];
for (var i=0; i<animateClasses.length; i++) {
(function(animCls) {
$('.each-brew.'+animCls).toggle(function() {
if (lastClicked && lastClicked != this) {
// animate it back
$(lastClicked).trigger('click');
}
lastClicked = this;
$('.each-brew-content.'+animCls).show().animate({ left: '0' }, 1000).css('position','inherit');
}, function() {
$('.each-brew-content.'+animCls)
.animate({ left: '-33.3333%' }, 1000, function() { $(this).hide()}) // hide the element in the animation on-complete callback
.css('position','relative');
});
})(animateClasses[i]); // self calling anonymous function
}
However, the content sliding out once the already open content slides back is sliding out too quickly - it needs to wait until the content has fully slided back in before it slides out. Is this possible?
Here's a link to what I'm currently working on to get an idea (http://goo.gl/s8Tl6).
Cheers in advance,
R
Here's my take on it as a drop-in replacement with no markup changes. You want one of three things to happen when a menu item is clicked:
if the clicked item is currently showing, hide it
if something else is showing, hide it, then show the current item's content
if nothing is showing, show the current item's content
var lastClicked = null;
// here lastClicked points to the currently visible content
var animateClasses = ['ale', 'bramling', 'bullet', 'miami-weisse'];
for (var i=0; i<animateClasses.length; i++) {
(function(animCls) {
$('.each-brew.'+animCls).click(function(event){
if(lastClicked && lastClicked == animCls){
// if the lastClicked is `this` then just hide the content
$('.each-brew-content.'+animCls).animate(
{ left: '-33.3333%' }, 1000,
function() {
$(this).hide();
}).css('position','relative');
lastClicked = null;
}else{
if(lastClicked){
// if something else is lastClicked, hide it,
//then trigger a click on the new target
$('.each-brew-content.'+lastClicked).animate(
{ left: '-33.3333%' }, 1000,
function() {
$(this).hide();
$(event.target).trigger('click');
}).css('position','relative');
lastClicked = null;
}else{
// if there is no currently visible div,
// show our content
$('.each-brew-content.'+animCls).show()
.animate({ left: '0' }, 1000)
.css('position','relative');
lastClicked = animCls;
}
}
});
})(animateClasses[i]); // self calling anonymous function
}
Well, I'm pretty sure there are other more easy possibilities and I didn't have much time but here is a working jsfiddle: http://jsfiddle.net/uaNKz/
Basicly you use the callback function to wait until the animation is complete. In this special case it's the complete: function(){...}
$("document").ready(function(){
$('#ale').click(function(){
if ($('div').hasClass('toggled')){
$('.toggled').animate({ width: "toggle" }, { duration:250, complete: function(){
$('#alecont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');}
}).removeClass('toggled');
}else{
$('#alecont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');
}
});
$('#bramling').click(function(){
if ($('div').hasClass('toggled')){
$('.toggled').animate({ width: "toggle" }, { duration:250, complete: function(){
$('#bramcont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');}
}).removeClass('toggled');
}else{
$('#bramcont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');
}
});
});
I give a toggled class if a div is expanded. Since the animation on your page seems to be pretty much broken I think this would be a better way to do this. But remember: my code isn't really good. Just fast and it can be refactored. It's working tho..
Rather than using toggles, bind an on "click" handler to your ".each-brew" divs. In the handler, first hide content divs and then show the appropriate content when that animation completes. You can do that with either a promise or a callback. Something like this...
$(".each-brew").on("click", function (event) {
$(".each-brew-content").show().animate({ left: "0" }, 1000, function() {
// Get the brew name from the class list.
// This assumes that the brew is the second class in the list, as in your markup.
var brew = event.currentTarget.className.split(/\s+/)[1];
$(".each-brew-content." + brew).animate({ left: "-33.3333%" }, 1000, function() { $(this).hide(); });
});
});
I think an event and observer would do the trick for you.
set up the callback function on completion of your animation to fire an event.
the listener would first listen for any animation event and after that event is triggered listen for the completion event. when the completion event is fired execute the initial animation event.run method (or whatever you would want to call it)
Within the listener
on newanimationeventtriger(new_anim) wait for x seconds (to eliminate infinite loop poss) while if this lastevent triggers done == true{
new_anim.run();
}

Prevent Double Animation in jQuery

How can I stop this function from happening twice when a user clicks too fast?
$(document).ready(function() {
$(".jTscroller a").click(function(event) {
event.preventDefault();
var target = $(this).attr("href");
$("#photo").fadeTo("fast", 0, function() {
$("#photo").attr("src",target);
$("#photo").load(function() {
$("#photo").fadeTo("fast", 1);
});
});
});
});
The issue I'm having is that if a user clicks too fast the element won't fade back in, it just stays hidden.
The issue wasn't what I thought it was. When I was clicking on the same thumbnail it would try to load in the same image and stick loading forever. The .stop() answer does fix double animation so I'm accepting that answer, but my solution was to check if the last clicked item was the currently displayed item. New script:
$(document).ready(function() {
$(".jTscroller a").click(function(event) {
event.preventDefault();
var last = $("#photo").attr("src");
var target = $(this).attr("href");
if (last != target) {
$("#photo").stop().fadeTo("fast", 0, function() {
$("#photo").attr("src",target);
$("#photo").load(function() {
$("#photo").fadeTo("fast", 1);
});
});
};
});
});
Well you use the correct word in your descripton. Use stop()
$("#photo").stop().fadeTo("fast", 0, function() {
You may use a setTimeout function to make a delay between click grabs. I mean, a second click will be processed only after sometime, after the first click. It sets an interval between clicks.
$(document).ready(function() {
var loaded = true;
$(".jTscroller a").click(function(event) {
if(!loaded) return;
loaded = false;
event.preventDefault();
var target = $(this).attr("href");
$("#photo").fadeTo("fast", 0, function() {
$("#photo").attr("src",target);
$("#photo").load(function() {
$("#photo").fadeTo("fast", 1);
loaded = true;
});
});
});
});
Keep track of its state
I believe what you are looking for is .stop()
http://api.jquery.com/stop/
$("#photo").stop(false, false).fadeTo()
I would prevent it like this:
var photo = $("#photo");
if (0 == photo.queue("fx").length) {
foto.fadeTo();
}
I differs from stop as it will only fire when all animations on this element are done. Also storing the element in a variable will save you some time, because the selector has to grab the element only once.
Use on() and off() :
$(document).ready(function() {
$(".jTscroller a").on('click', changeImage);
function changeImage(e) {
e.preventDefault();
$(e.target).off('click');
$("#photo").fadeOut("fast", function() {
this.src = e.target.href;
this.onload = function() {
$(this).fadeIn("fast");
$(e.target).on('click', changeImage);
});
});
}
});

Categories