Changing event to on.click for searching terms - javascript

I have this snippet found below which highlights and jumps to the searched term. The current snippet searches after each keystroke that the user inputs which is putting too much stress on the server. Instead I want it to mark and jump once the user presses enter or clicks the next button. I've tried change the following line but it's breaking the code. Any ideas?
$input.on("input", function() {
to
$nextBtn.on('click', function() {
Code here:
$(function() {
// the input field
var $input = $("input[type='search']"),
// clear button
$clearBtn = $("button[data-search='clear']"),
// prev button
$prevBtn = $("button[data-search='prev']"),
// next button
$nextBtn = $("button[data-search='next']"),
// the context where to search
$content = $(".content"),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 50,
// the current index of the focused element
currentIndex = 0;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results.eq(currentIndex);
$results.removeClass(currentClass);
if ($current.length) {
$current.addClass(currentClass);
position = $current.offset().top - offsetTop;
window.scrollTo(0, position);
}
}
}
/**
* Searches for the entered keyword in the
* specified context on input
*/
$input.on("input", function() {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
});
/**
* Clears the search
*/
$clearBtn.on("click", function() {
$content.unmark();
$input.val("").focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.add($prevBtn).on("click", function() {
if ($results.length) {
currentIndex += $(this).is($prevBtn) ? -1 : 1;
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
jumpTo();
}
});
});
Working JSFiddle found here: https://jsfiddle.net/83nbm2rv/

You can change the $input.on('input') to:
$input.on("keypress", function(e) {
if (e.which === 13) {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
}
});
And that will handle pressing enter in the textbox. See this fiddle for the next button click update: https://jsfiddle.net/9g4xr765/
Basic approach was to functionalize the content marking and calling it on $input keypress, and also in next/previous click if there are no results.
There are still issues though, like if the value changes you can't use the next/previous button to search so that would require some additional work.

Related

Disable Tooltip in jQuery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a little problem I'd like to solve.
https://byobcreatubolso.com/producto/sario-sart/
I have tooltip enabled inside my js code.
When the user clicks on the bag image, a thumbnail is displayed. I would like the samples to appear when the page loads without clicking on the bag image.
Any idea how to solve it? Thanks.
jQuery(document).ready(function() {
jQuery('.select-zone .seccion_imagen').css('cursor', 'pointer');
jQuery('.iconic-was-swatches__label').css('cursor', 'pointer');
jQuery('.js-toggle-next').css('cursor', 'pointer');
//First hide elements
jQuery('.variations .label label').hide();
jQuery('.variations .value').hide();
jQuery('.iconic-was-swatches__item').hide();
// Show first level
jQuery('.select-zone .seccion_imagen').on('click touchstart', function(event) {
jQuery('.select-zone .seccion_imagen').removeClass('selected');
jQuery(this).addClass('selected');
jQuery('.variations .value').hide('slow');
jQuery('.iconic-was-swatches__item').hide('slow');
var elemento = jQuery(this).attr('id');
jQuery('[for=' + elemento + ']').parent().next('.value').show('slow');
jQuery('[for=' + elemento + ']').parent().next('.value').children('ul').children('.iconic-was-swatches__label:first').nextUntil('.iconic-was-swatches__label').css('display', 'inline-block');
});
// Show second level
jQuery('.iconic-was-swatches__label').on('click touchstart', function(event) {
jQuery('.iconic-was-swatches__label').hide();
jQuery('.iconic-was-swatches__item').hide();
jQuery(this).nextUntil('.iconic-was-swatches__label').css('display', 'inline-block');
});
// Get selected values and draw in rigth place
jQuery(document).on('change', '.variations select', function() {
var selectID = jQuery(this).attr('id'),
selectedAttributte = jQuery(this).text(),
selectedValue = jQuery(this).val(),
CapitalValue = selectedValue.charAt(0).toUpperCase() + selectedValue.slice(1);
console.log('Select id ' + selectID);
console.log('Select attr ' + selectedAttributte);
console.log('Selected value ' + selectedValue);
jQuery('#js-selected-' + selectID).text(CapitalValue);
});
// Stamped text
jQuery('.js-toggle-next').on('click', function(event) {
jQuery(this).next('div').toggle('slow');
jQuery(this).next('div').next('label').next('input').val('');
});
jQuery('.stamped-text-input').on('keyup', function() {
if (!jQuery(this).val()) {
jQuery('#js-stamped-text-selected-container').addClass('d-none');
jQuery('#js-stamped-text-notice').addClass('d-none');
} else {
jQuery('#js-stamped-text-selected-container').removeClass('d-none');
jQuery('#js-stamped-text-notice').removeClass('d-none');
jQuery('#js-stamped-text-selected').text(jQuery(this).val());
jQuery('#js-stamped-text-sniffer').val(jQuery(this).val());
}
});
jQuery('[data-toggle="tooltip"]').tooltip()
// TO-DO move add to cart to rigth side
//jQuery('.single_variation_wrap').appendTo('#js-ad-to-cart');
// Move price variation
jQuery('.single_variation_wrap').on('change', function() {
if (jQuery('form.variations_form').length !== 0) {
var form = jQuery('form.variations_form'),
variable_product_price = '';
if (jQuery('.single_variation_wrap span.price span.amount').length !== 0) {
if (jQuery('#summary .entry-summary p.price span.amount').text() !== variable_product_price) {
variable_product_price = jQuery('.single_variation_wrap span.price span.amount').html();
jQuery('#summary .entry-summary p.price').html('');
jQuery('#summary .entry-summary p.price').html(variable_product_price);
}
}
}
});
});
/**
* jQuery 2.0+ REQUIRED
* ==============================================
* iOS9 'click', 'mousedown' and 'mouseup' fix
* ---------------------------------------------
* Include this script in your poject to fix 'click', 'mousedown' and 'mouseup' event
* handling for $(window), $(document), $('body') and $('html'). By default iOS9 Safari is
* suppressing those events in some situations and without some magic they can't be rely on.
* This fix is blocking native event handlers from firing
* (in some rare cases event will reach it's destination)
* and it handles native event handlers basing on 'touchstart' and 'touchend' event.
* ---------------------------------------------
* Use at your own risk
*/
(function($) {
$(document).ready(function() {
if (typeof navigator.userAgent == 'undefined' || !navigator.userAgent.match(/(iPad|iPhone|iPod)/i)) {
return;
}
var EVENT_NAMESPACE = 'IOS9FIX';
var MAX_DOM_DEPTH = 100;
/**
* Suppress event for $object.
* #param $object
* #param eventType
*/
var blockEventFor = function($object, eventType) {
var eventQueue, eventRepo = new Array();
if ($._data($object.get(0), "events") !== undefined) {
eventQueue = $._data($object.get(0), "events")[eventType];
}
if (eventQueue !== undefined) {
for (var i = 0; i < eventQueue.length; i++) {
eventRepo.push({
handler: eventQueue[i].handler,
selector: eventQueue[i].selector,
namespace: eventQueue[i].namespace
});
}
$object.off(eventType);
}
$object.on(eventType + '.' + EVENT_NAMESPACE, '*', function(event) {
event.stopImmediatePropagation();
});
for (var i = 0; i < eventRepo.length; i++) {
var _eventType = eventRepo[i].namespace ?
eventType + '.' + eventRepo[i].namespace :
eventType;
$object.on(_eventType, eventRepo[i].selector, eventRepo[i].handler);
}
};
var executeMockedEventHandlers = function($object, mockedEventType, originalEvent) {
/** Let's say touch is mouse left button (by default touch event has .which === 0) */
originalEvent.which = 1;
var mockedEventQueue, $target = $(originalEvent.target);
if ($._data($object.get(0), "events") !== undefined) {
mockedEventQueue = $._data($object.get(0), "events")[mockedEventType];
}
/** No event-handlers for event of such type */
if (mockedEventQueue === undefined) {
return false;
}
for (var preventEndlessLoop = 0; preventEndlessLoop < MAX_DOM_DEPTH; preventEndlessLoop++) {
/** END THE LOOP */
if ($target.length == 0) {
break;
}
/** EXECUTE MOCKED EVENT HANDLERS */
for (var i = 0; i < mockedEventQueue.length; i++) {
// Skip eventHandler used to block originalEvent for mockedEvent
if (mockedEventQueue[i].namespace === EVENT_NAMESPACE) {
continue;
}
if (mockedEventQueue[i].selector === undefined) {
// Skip $object level eventHandlers until current DOM level is $object level
if (!$target.is($object[0])) {
continue;
}
} else {
// Skip eventHandlers not meant for current DOM level
if (!$target.is(mockedEventQueue[i].selector)) {
continue;
}
}
// Execute handler for current DOM level
if (mockedEventQueue[i].handler.call($target[0], originalEvent) === false) {
originalEvent.stopImmediatePropagation();
}
// Check for stopImmediatePropagation() */
if (originalEvent.isImmediatePropagationStopped()) {
break;
}
}
if (originalEvent.isPropagationStopped()) {
break;
}
/** Go to parent level */
$target = $target.parent();
}
};
/*****************************
* INITIALIZATION
****************************/
/**
* Go through objects and suppress all selected events.
*/
$.each([$(document), $(window), $('body'), $('html')], function(objectIndex, $object) {
$.each(['mousedown', 'click', 'mouseup'], function(eventIndex, eventType) {
blockEventFor($object, eventType);
});
});
/**
* Init MouseDown-Mock for Dom $object
* #param $object
*/
var initMouseDownMock = function($object) {
$object.on('touchstart', function(event) {
executeMockedEventHandlers($object, 'mousedown', event);
});
};
$.each([$(document), $(window), $('body'), $('html')], function(objectIndex, $object) {
initMouseDownMock($object);
});
var initMouseUpMock = function($object) {
$object.on('touchend', function(event) {
executeMockedEventHandlers($object, 'mouseup', event);
});
};
/**
* Init MouseUp-Mock for objects...
*/
$.each([$(document), $(window), $('body'), $('html')], function(objectIndex, $object) {
initMouseUpMock($object);
});
/**
* MOCK CLICK EVENT
*/
/**
* Init Click-Mock for Dom $object
* #param $object
*/
var initClickMock = function($object) {
var clickCancelationTimer, isClick, cursorX, cursorY, target;
$object.on('touchstart', function(event) {
isClick = true;
cursorX = event.originalEvent.touches[0].pageX;
cursorY = event.originalEvent.touches[0].pageY;
target = event.target;
/** Click Timeout */
clickCancelationTimer = setTimeout(function() {
isClick = false;
}, 300);
});
/** moved more than 10 px away from starting position */
$object.on('touchmove', function(event) {
if (Math.abs(cursorX - event.originalEvent.touches[0].pageX) > 10 || Math.abs(cursorY - event.originalEvent.touches[0].pageY) > 10) {
isClick = false;
}
});
$object.on('touchend', function(event) {
clearTimeout(clickCancelationTimer);
if (isClick) {
executeMockedEventHandlers($object, 'click', event);
}
});
};
/**
* Init Click-Mock for objects...
*/
$.each([$(document), $(window), $('body'), $('html')], function(objectIndex, $object) {
initClickMock($object);
});
});
})(jQuery);
you can disable the tooltips for all the elements and enable it on the one you need it to be in. try this:
$('*').tooltip();
this will put a tooltip on all elements.
you can disable the tooltip from all elements like so as well:
$('*').tooltip('disable');
if you want a specific element then select it and enable/disable it. here's a question on this site that might help you as well:
Turn off jQuery UI tooltip for certain elements

Highlighting with mark.js working for only 1-3 letters

I'm trying to implement mark.js on a page, but it isn't working correctly. So I setup a very basic page, and pulled all of the code from this jsfiddle page, however it will only highlight certain 1-3 letters at a time, depending on whatever I put in. Can anyone see what I'm doing wrong exactly? My page is located here.
Code:
$(function() {
// the input field
var $input = $("input[type='search']"),
// clear button
$clearBtn = $("button[data-search='clear']"),
// prev button
$prevBtn = $("button[data-search='prev']"),
// next button
$nextBtn = $("button[data-search='next']"),
// the context where to search
$content = $(".content"),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 50,
// the current index of the focused element
currentIndex = 0;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results.eq(currentIndex);
$results.removeClass(currentClass);
if ($current.length) {
$current.addClass(currentClass);
position = $current.offset().top - offsetTop;
window.scrollTo(0, position);
}
}
}
/**
* Searches for the entered keyword in the
* specified context on input
*/
$input.on("input", function() {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
});
/**
* Clears the search
*/
$clearBtn.on("click", function() {
$content.unmark();
$input.val("").focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.add($prevBtn).on("click", function() {
if ($results.length) {
currentIndex += $(this).is($prevBtn) ? -1 : 1;
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
jumpTo();
}
});
});
This ended up being an encoding issue. Adding:
<meta charset="UTF-8">
resolved the problem.

How to trigger an event for on(event)

I want to trigger an event to execute code wrapped in $('.selector').on('event').
The selector change just before I trigger the event.
To understand the problem : I have a text on page 1 and the function trigger a click to go to the page 2 (this works btw!). So now I'm on page 2 and I want to trigger a click to execute code in on() method. And this doesn't work.
I've tried many things and nothing works, the only way to execute the code in on() method is to manually click on the selector.
This is the entire code actually :
jQuery(function() {
// the input field
$input = jQuery("input[type=\'search\']");
// clear button
var $clearBtn = jQuery("button[data-search=\'clear\']"),
// prev button
$prevBtn = jQuery("button[data-search=\'prev\']"),
// next button
$nextBtn = jQuery("button[data-search=\'next\']"),
// the context where to search
$content = jQuery(".search_content"),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 50,
// the current index of the focused element
currentIndex = 0,
//the current ajaxpage
currentPage = 1;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results.eq(currentIndex);
$results.removeClass(currentClass);
if ($current.length) {
$current.addClass(currentClass);
position = $current.offset().top - offsetTop - 100;
window.scrollTo(0, position);
}
}
}
var mark = function() {
// Read the keyword
var keyword = $input.val();
// empty options
var options = {};
// Remove previous marked elements and mark
// the new keyword inside the content
jQuery(".search_content").unmark({
done: function() {
jQuery(".search_content").mark(keyword, options);
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
};
function registerClear() {
$input.on("input", function() {
searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
console.log(searchVal);
console.log("page2");
jumpTo();
}
});
}
});
});
}
registerClear();
/**
* Clears the search
*/
$clearBtn.on("click", function() {
$content.unmark();
$input.val("").focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.add($prevBtn).on("click", function() {
if ($results.length) {
currentIndex += jQuery(this).is($prevBtn) ? -1 : 1;
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
//TODO : - LINK DONE - SEARCH ON EACH PAGE IF THERE ARE OCCURENCE
if (currentIndex == 0 && jQuery(this).is($nextBtn)) {
if (confirm("No more instances found! Go to the next page?")) {
alert("NEXT PAGE");
jQuery("a[data-page=\'2\']").click();
jQuery(document).ready(function() {
jQuery(".search_content").click();
});
jQuery(document.body).on("click", ".search_content", mark)
registerClear();
} else {
//do nothing
}
}
jumpTo();
}
});
});
this is the important part:
if (currentIndex == 0 && jQuery(this).is($nextBtn)) {
if (confirm("No more instances found! Go to the next page?")) {
alert("NEXT PAGE");
jQuery("a[data-page=\'2\']").click();
jQuery(document).ready(function() {
jQuery(".search_content").click();
});
jQuery(document.body).on("click", ".search_content", mark)
registerClear();
} else {
//do nothing
}
}
What I've tried :
I've search many things on SO.
Since the content on which I trigger the event is loaded via ajax I thought it was because I triggered the event to soon, so I've tried wrapping my code in document.ready, or with setTimeOut function. No results.
I've tried this :
jQuery('#bar')[0].click();
This :
jQuery(document).ready(function(){
jQuery('#foo').on('click', function(){
jQuery('#bar').simulateClick('click');
});
});
jQuery.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE Boss!
}
});
}
I've tried putting the trigger after the on() method.
I've tried changing the element on which I do the event.
And also changing the event triggered.
Now I feel like I've tried everything, so I am asking for your help please.
$('element_selector').trigger('eventname', param1, param2,...);
this will trigger given event, params are optional if required

How can I make a field NOT required in this code?

So I took this code from this website. I don't want to have all the fields being required. Like, let's say, full middle name. I want that field to be optional (hence, not affecting the function for checking which fields have error). How can I do it?
$(function() {
/*
number of fieldsets
*/
var fieldsetCount = $('#formElem').children().length;
/*
current position of fieldset / navigation link
*/
var current = 1;
/*
sum and save the widths of each one of the fieldsets
set the final sum as the total width of the steps element
*/
var stepsWidth = 0;
var widths = new Array();
$('#steps .step').each(function(i){
var $step = $(this);
widths[i] = stepsWidth;
stepsWidth += $step.width();
});
$('#steps').width(stepsWidth);
/*
to avoid problems in IE, focus the first input of the form
*/
$('#formElem').children(':first').find(':input:first').focus();
/*
show the navigation bar
*/
$('#navigation').show();
/*
when clicking on a navigation link
the form slides to the corresponding fieldset
*/
$('#navigation a').bind('click',function(e){
var $this = $(this);
var prev = current;
$this.closest('ul').find('li').removeClass('selected');
$this.parent().addClass('selected');
/*
we store the position of the link
in the current variable
*/
current = $this.parent().index() + 1;
/*
animate / slide to the next or to the corresponding
fieldset. The order of the links in the navigation
is the order of the fieldsets.
Also, after sliding, we trigger the focus on the first
input element of the new fieldset
If we clicked on the last link (confirmation), then we validate
all the fieldsets, otherwise we validate the previous one
before the form slided
*/
$('#steps').stop().animate({
marginLeft: '-' + widths[current-1] + 'px'
},500,function(){
if(current == fieldsetCount)
validateSteps();
else
validateStep(prev);
$('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();
});
e.preventDefault();
});
/*
clicking on the tab (on the last input of each fieldset), makes the form
slide to the next step
*/
$('#formElem > fieldset').each(function(){
var $fieldset = $(this);
$fieldset.children(':last').find(':input').keydown(function(e){
if (e.which == 9){
$('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
/* force the blur for validation */
$(this).blur();
e.preventDefault();
}
});
});
/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateStep(step){
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == '')
{
hasError = true;
$this.css('background-color','red');
}
else
{
$this.css('background-color','yellow');
}
}
);
var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError)
{
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
/*
if there are errors don't allow the user to submit
*/
$('#registerButton').bind('click',function(){
if($('#formElem').data('errors')){
alert('Please correct the errors in the Form');
return false;
}
});
});
inside validateStep function on line where you perform the find just add this tag after :input like below:
$('#formElem').children(':nth-child('+ parseInt(step)+')').find(':input[required]:not(button)')
You just have to use the required html attribute inside your web page and when you will run the validateStep function, it will ignore all fields without the required attribute.
look at mdn doc for more informations.
https://developer.mozilla.org/en-US/docs/Web/CSS/:required

javascript 'over-clicking' bug

I have a bug in Javascript where I am animating the margin left property of a parent container to show its child divs in a sort of next/previous fashion. Problem is if clicking 'next' at a high frequency the if statement seems to be ignored (i.e. only works if click, wait for animation, then click again) :
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
//roll margin back to 0
}
An example can be seen on jsFiddle - http://jsfiddle.net/ZQg5V/
Any help would be appreciated.
Try the below code which will basically check if the container is being animated just return from the function.
Working demo
$next.click(function (e) {
e.preventDefault();
if($contain.is(":animated")){
return;
}
var marLeft = $contain.css('margin-left'),
$this = $(this);
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
$contain.animate({
marginLeft: 0
}, function () {
$back.fadeOut('fast');
});
} else {
$back.fadeIn(function () {
$contain.animate({
marginLeft: "-=" + regWidth + "px"
});
});
}
if (marLeft > -combinedWidth) {
$contain.animate({
marginLeft: 0
});
}
});
Sometimes is better if you create a function to take care of the animation, instead of writting animation code on every event handler (next, back). Also, users won't have to wait for the animation to finish in order to go the nth page/box.
Maybe this will help you:
if (jQuery) {
var $next = $(".next"),
$back = $(".back"),
$box = $(".box"),
regWidth = $box.width(),
$contain = $(".wrap")
len = $box.length;
var combinedWidth = regWidth*len;
$contain.width(combinedWidth);
var currentBox = 0; // Keeps track of current box
var goTo = function(n) {
$contain.animate({
marginLeft: -n*regWidth
}, {
queue: false, // We don't want animations to queue
duration: 600
});
if (n == 0) $back.fadeOut('fast');
else $back.fadeIn('fast');
currentBox = n;
};
$next.click(function(e) {
e.preventDefault();
var go = currentBox + 1;
if (go >= len) go = 0; // Index based, instead of margin based...
goTo(go);
});
$back.click(function(e) {
e.preventDefault();
var go = currentBox - 1;
if (go <= 0) go = 0; //In case back is pressed while fading...
goTo(go);
});
}
Here's an updated version of your jsFiddle: http://jsfiddle.net/victmo/ZQg5V/5/
Cheers!
Use a variable to track if the animation is taking place. Pseudocode:
var animating = false;
function myAnimation() {
if (animating) return;
animating = true;
$(this).animate({what:'ever'}, function() {
animating = false;
});
}
Crude, but it should give you the idea.
Edit: Your current code works fine for me as well, even if I jam out on the button. On firefox.

Categories

Resources