Disable Tooltip in jQuery [closed] - javascript

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

Related

Changing event to on.click for searching terms

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.

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

jquery call a function each time a class has changed

This is the markup for my navigation:
<div class="navigation navigation-fixed-top">
Home
About
</div>
And I have this jquery script, which is checking if href="#home" has class active to do something and if not to do something else.
This is the code:
var isActive = $('a[href="#home"]').hasClass('active');
$(".navigation")
.toggleClass("navigation-fixed-bottom", isActive)
.toggleClass("navigation-fixed-top", !isActive);
This is partially working because the class="active" is added automatically when I'm going the #about section or I'm clicking on it. It does this without refreshing the page so I need a way to to make this work without refreshing the page.
Any suggestions on how can I do this with jQuery/Javascript ?
UPDATE:
this is the name of the plugin Scrollit.js
THIS IS THE CODE RESPONSIBLE FOR ADDING THE ACTIVE CLASS ON THE NAVIGATION ELEMENTS:
(function($) {
'use strict';
var pluginName = 'ScrollIt',
pluginVersion = '1.0.3';
/*
* OPTIONS
*/
var defaults = {
upKey: 38,
downKey: 40,
easing: 'linear',
scrollTime: 600,
activeClass: 'active',
onPageChange: null,
topOffset : 0
};
$.scrollIt = function(options) {
/*
* DECLARATIONS
*/
var settings = $.extend(defaults, options),
active = 0,
lastIndex = $('[data-scroll-index]:last').attr('data-scroll-index');
/*
* METHODS
*/
/**
* navigate
*
* sets up navigation animation
*/
var navigate = function(ndx) {
if(ndx < 0 || ndx > lastIndex) return;
var targetTop = $('[data-scroll-index=' + ndx + ']').offset().top + settings.topOffset + 1;
$('html,body').animate({
scrollTop: targetTop,
easing: settings.easing
}, settings.scrollTime);
};
/**
* doScroll
*
* runs navigation() when criteria are met
*/
var doScroll = function (e) {
var target = $(e.target).closest("[data-scroll-nav]").attr('data-scroll-nav') ||
$(e.target).closest("[data-scroll-goto]").attr('data-scroll-goto');
navigate(parseInt(target));
};
/**
* keyNavigation
*
* sets up keyboard navigation behavior
*/
var keyNavigation = function (e) {
var key = e.which;
if(key == settings.upKey && active > 0) {
navigate(parseInt(active) - 1);
return false;
} else if(key == settings.downKey && active < lastIndex) {
navigate(parseInt(active) + 1);
return false;
}
return true;
};
/**
* updateActive
*
* sets the currently active item
*/
var updateActive = function(ndx) {
if(settings.onPageChange && ndx && (active != ndx)) settings.onPageChange(ndx);
active = ndx;
$('[data-scroll-nav]').removeClass(settings.activeClass);
$('[data-scroll-nav=' + ndx + ']').addClass(settings.activeClass);
};
/**
* watchActive
*
* watches currently active item and updates accordingly
*/
function navPosition() {
$('[data-scroll-nav]').toggleClass('navigation-fixed-bottom navigation-fixed-top');
}
var updateActive = function(ndx, navPosition) {
var watchActive = function() {
var winTop = $(window).scrollTop();
var visible = $('[data-scroll-index]').filter(function(ndx, div) {
return winTop >= $(div).offset().top + settings.topOffset &&
winTop < $(div).offset().top + (settings.topOffset) + $(div).outerHeight()
});
var newActive = visible.first().attr('data-scroll-index');
updateActive(newActive);
};
/*
* runs methods
*/
$(window).on('scroll',watchActive).on('scroll');
$(window).on('keydown', keyNavigation);
$('body').on('click','[data-scroll-nav], [data-scroll-goto]', function(e){
e.preventDefault();
doScroll(e);
});
};
}(jQuery));
$('[data-scroll-nav]').removeClass(settings.activeClass)
.toggleClass('navigation-fixed-bottom navigation-fixed-top');
and/or
$('[data-scroll-nav=' + ndx + ']').addClass(settings.activeClass)
.toggleClass('navigation-fixed-bottom navigation-fixed-top');
If you wanted to keep the original code cleaner, you could do a callback:
function myCallBackFunction() {
$('[data-scroll-nav]').toggleClass('navigation-fixed-bottom navigation-fixed-top');
}
var updateActive = function(ndx, myCallbackFunction) {..}
use jquery on to bind handlers to events you want to respond
$("a.active").on('click',function(){});

jQuery.appear to fire only when the entire element in is viewport

I'm currently using jQuery.appear to change the class of elements as they come into the viewport. The plugin works great, except that it fires right as the top of the element comes into view. I am wanting to adapt it so it only fires when the entire element is inside the viewport, or near to being.
CODE:
$('someselector').appear();
$('someselector').on('appear', function() {
$(this).removeClass('on').addClass('off');
$(this).siblings().removeClass('off').addClass('on');
});
jQuery Waypoints plugin could be useful also. It triggers an action, when the element became to be visible on the screen.
$('.entry').waypoint(function() {
alert('The element is appeared on the screen.');
});
There are some examples on the site of the plugin.
I have changed some of the code so you can check if an element is fully visible. Removed the code that will trigger an event since it's harder to clean up using destroy (not implemented yet). I will try and make it according to the documentation: http://docs.jquery.com/Plugins/Authoring
Here is the html page:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="appear.js"></script>
<script>
$(document).ready(function(){
//TODO: not sure if there is such a thing as selector
// namespaces but could try that to add both appear and
// fully-appear to same selector elements
$('#fully').appear(function(){
console.log("full view");
},{fullView:true});
$('#partly').appear(function(){
console.log("partly visible");
});
$(window).scrollTop(1400).scrollLeft(1000);
});
</script>
</head>
<body >
<div style="width:3000px;height: 3000px"></div>
<div id="fully" style="width:50px;height:75px;
position: absolute;left:1500px;top:1500px;
background: black">
</div>
<div id="partly" style="width:50px;height:75px;
position: absolute;left:1450px;top:1350px;
background: yellow">
</div>
</body>
</html>
And the changed appear.js
/*
* jQuery appear plugin
*
* Copyright (c) 2012 Andrey Sidorov
* licensed under MIT license.
* Edit by HRM 2013 02 01
* https://github.com/morr/jquery.appear/
*
* Version: 0.2.1
*/
(function($) {
var selectors = [];
var $window = $(window);
var $document = $(document);
function process(p) {
p.checkLock = false;
var $appeared = p.elements.filter(function() {
return $(this).is(p.filterName);
});
if($appeared.length==0){
return;
}
p.callback($appeared);
}
// "appeared" custom filter
$.expr[':']['appeared'] = function(element) {
var $element = $(element);
if (!$element.is(':visible')) {
return false;
}
var window_left = $window.scrollLeft();
var window_top = $window.scrollTop();
var offset = $element.offset();
var left = offset.left;
var top = offset.top;
if (top + $element.height() >= window_top &&
top - ($element.data('appear-top-offset') || 0)
<= window_top + $window.height() &&
left + $element.width() >= window_left &&
left - ($element.data('appear-left-offset') || 0)
<= window_left + $window.width()) {
return true;
} else {
return false;
}
}
// "in-full-view" custom filter
$.expr[':']['fully-appeared'] = function(element) {
var $element = $(element);
if (!$element.is(':visible')) {
return false;
}
wLeft=$window.scrollLeft();
wTop=$window.scrollTop();
var offset = $element.offset();
var left = offset.left- ($element.data
('appear-left-offset') || 0);
var right = (offset.left+$element.width()) -
($element.data('appear-left-offset') || 0);
var top = offset.top - ($element.data
('appear-top-offset') || 0);
var bottom = offset.top+$element.height();
var window_left = wLeft;
var window_top = wTop;
var window_right = wLeft+ $window.width();
var window_bottom = wTop+$window.height();
if (window_bottom>=bottom&&
window_top<=top&&
window_left<=left&&
window_right>=right ) {
return true;
} else {
return false;
}
}
function compare(o1,o2){
//simple compare, assumes all properties of o1 and o2 are
// simple types make sure that o1 is not undefined
// comparing goes much further but requires writing another
// extension
if(typeof o2=="undefined"){
return false;
}
var i;
for(i in o1){
if(typeof o2[i]=="undefined"){
return false;
}
}
for(i in o1){
if(o1[i]!=o2[i]){
return false;
}
}
return true;
}
function checkExist(selector){
return !(typeof selectors[selector]=="undefined");
}
$.fn.extend({
// watching for element's appearance in browser viewport
appear: function(callback, options) {
if(typeof callback != "function"){
throw("Have to provide a callback: "
+"$('selector').appear(function()....");
}
var defaults = {
interval: 250
}
var index=this.selector;
if(index==""){
throw("Can't use an empty selector with this function.");
}
$.extend(defaults, options || {});
var exist=checkExist(index);
if(!exist){
selectors[index]=defaults;
}
var checkBind=compare(defaults,
selectors[index]);
selectors[index]=defaults;
var p={
checkLock:false,
filterName:(defaults.fullView)?":fully-appeared":":appeared",
callback:callback,
elements:this
}
if ((!checkBind)||(!exist)) {
$(window).off("scroll."+index,on_check)
.on("resize."+index,on_check);
var on_check = function() {
if (p.checkLock) {
return;
}
p.checkLock = true;
setTimeout(function(){
process(p);
}, defaults.interval);
};
$(window).on("scroll."+index,on_check)
.on("resize."+index,on_check);
}
if (options && options.force_process) {
setTimeout(process, defaults.interval);
}
return $(this.selector);
}
});
$.extend({
// force elements's appearance check
force_appear: function() {
if (check_binded) {
process();
return true;
};
return false;
}
});
})(jQuery);

Categories

Resources