Category: jQuery

Onscroll animations jquery

Below code to we can set animation son scroll nested time

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css">
<style>
.revealOnScroll{opacity:0;}
</style>

For jQuery used below function


<script src="//ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.js"></script>

<script>
//Update this function call with your own element ID, animate.css animation, and timeout in milliseconds. Each animated element requires its on function call.
//Supported animations are 'fadeInUp' 'flipInX' 'lightSpeedIn' 'bounceIn' 'slideInLeft' 'slideInRight' 'fadeInLeft' 'fadeInRight'. Other animations must be added on line 41 if used.
addAnimationData('#lp-pom-image-126','bounceIn','1000');
//addAnimationData('#your-next-element','bounceIn','2000');

function addAnimationData(elem, elemData, elemTimeout) {
$(elem).addClass("revealOnScroll").attr("data-animation",elemData).attr("data-timeout",elemTimeout);
}
$(function() {
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
if (isTouch) { $('.revealOnScroll').addClass('animated'); }
$window.on('scroll', revealOnScroll);
function revealOnScroll() {
var scrolled = $window.scrollTop(),
win_height_padded = $window.height() * 1.1;
// Showed...
$(".revealOnScroll:not(.animated)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function(){
$this.addClass('animated ' + $this.data('animation'));
}, parseInt($this.data('timeout'),10));
} else {
$this.addClass('animated ' + $this.data('animation'));
}
}
});
// Hidden...
$(".revealOnScroll.animated").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
//add additional animate.css animations to the removeClass function
$(this).removeClass('animated fadeInUp flipInX lightSpeedIn bounceIn slideInLeft slideInRight fadeInLeft fadeInRight')
}
});
}
revealOnScroll();
});
//Original script created by BenoƮt Boucart: http://blog.webbb.be/
/**
* Do not remove this section; it allows our team to troubleshoot and track feature adoption.
* TS:0002-03-037
*/
</script>

Refrence

Advertisements

jQuery equal height based on rows listing


// =========================
// Equal height of Box base design.
// =========================
equalheight = function (container) {
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
jQueryel,
topPosition = 0;
jQuery(container).each(function () {
jQueryel = jQuery(this);
jQuery(jQueryel).height('auto')
topPostion = jQueryel.position().top;

if (currentRowStart != topPostion) {
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = jQueryel.height();
rowDivs.push(jQueryel);
} else {
rowDivs.push(jQueryel);
currentTallest = (currentTallest < jQueryel.height()) ? (jQueryel.height()) : (currentTallest);
}
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}

// =========================
// Call Equal height function
// =========================
jQuery(window).load(function() {
equalheight('.class_name');
});
jQuery(window).resize(function(){
equalheight('.class_name');
});

Call jQuery function after all image are load

Some time we need to set equal height in our design. using below snippet we can easily call function or custom code.


// =============================================
// load portfolio list
// =============================================
function load_portfolio_list( post_length ) {

var category_id = jQuery(".portfolio-list").data('category_id');
jQuery( '.portfolio-ajax' ).addClass('loading');
jQuery.ajax({
type: "POST",
url: adminurl,
dataType: 'json',
data: { action : 'load_portfolio', post_length : post_length, category_id : category_id},
success: function (result){
jQuery('.portfolio-list .portfolio-ajax').remove();
jQuery('.portfolio-list .row').append(result.portfolio_list).imagesLoaded().then(function(){
equalheight('.portfilio-item');
});
},
error:function(){
alert("Error: There is some issue please try again.");
},
beforeSend:function(){
jQuery( '.portfolio-ajax' ).addClass('loading');
},
complete: function () {
jQuery( '.portfolio-ajax' ).removeClass('loading');
// Our code after load
}
});
}

below code are check image are loading after done function will return


// Fn to allow an event to fire after all images are loaded
jQuery.fn.imagesLoaded = function ($) {

// get all the images (excluding those with no src attribute)
var $imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return jQuery.Deferred().resolve().promise();}

// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
var dfds = [];
$imgs.each(function(){

var dfd = jQuery.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.onerror = function(){dfd.resolve();}
img.src = this.src;

});

// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return jQuery.when.apply(jQuery,dfds);

}

How to override javascript file in wordpress

Some time we required to override plugin and theme jQuery file to used below script.
if override plugin file add in your theme functions.php file and override theme file to add on child theme functions.php file.

function checkout_script(){
	wp_dequeue_script('wc-checkout');	
	wp_enqueue_script( 'wc-checkout', get_bloginfo( 'stylesheet_directory' ). '/woocommerce/assets/checkout.js' , array( 'jquery' ), false, true );	
}

add_action( 'wp_enqueue_scripts', 'checkout_script',1 ); 

jQuery first click disable

First click disable in all devise.

jQuery(".subnav a").one("click", false);

First click disable in Mobile devise.

jQuery( document ).ready( function( $ ) {
var isMobile = /iPad|iPhone|Android|iPod/i.test(navigator.userAgent);
	//alert (isMobile);
if (isMobile) {
	
	jQuery(".home-product a, .cart-product a").click(function(e){
		e.preventDefault();
		jQuery(".home-product a").addClass('nav_returnlink');
		jQuery(this).unbind('click');
		//don't actually need to do anything, just want the handler so that css fires in iOS
	});
});

Get value for element using jquery

Get html control[like input, select,checkbook, etc] values using jQuery they are some method as like bellow.

<!--Input Box Method 1 -->
var inputval = $('#txt_name').val();

<!--Input Box Method 2 -->
var inputval = $('#txt_name').attr("value");

<!--Input Box Method 3 this this is good method -->
var inputval = $('#txt_name').prop("value");

<!--Select Box Method 1 -->
var selectval = $('#select_val').val();

<!--Select Box Method 2 -->
var selectval = $('#select_val').attr("value");

<!--Select Box Method 3 this this is good method -->
var selectval = $('#select_val').prop("value");

Create cookie using javascript

in bellow JavaScript function are create cookie and get cookie with path, expire time.

// Create new Cookies
	setCookie("dalwadi_tab", 'dalwaditab', 30,'admin');
	
	// get Cookies
	var activeTab=getCookie("dalwadi_tab");	
	alert(activeTab);
	
	
	// Create new Cookies function
	function setCookie(Cookiename,Cookievalue,exdays,Cookiepath) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays*24*60*60*1000));
		var expires = "expires=" + d.toGMTString();
		document.cookie = Cookiename+"="+Cookievalue+"; "+expires + path+"/"+Cookiepath;
	}
	// get Cookies function
	function getCookie(Cookiename) {	
		var name = Cookiename + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i<ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1);
			if (c.indexOf(name) == 0) {
				return c.substring(name.length, c.length);
			}
		}
		return "";
	}

Redirect when user closes window or tab

Is there a way to redirect the window or tab when a user closes it.

<script language="javascript">
(function() {
    setTimeout(function() {
    var __redirect_to = 'http://google.com';//

    var _tags = ['button', 'input', 'a'], _els, _i, _i2;
    for(_i in _tags) {
        _els = document.getElementsByTagName(_tags[_i]);
        for(_i2 in _els) {
            if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
            _els[_i2].onclick = function() {window.onbeforeunload = function(){};}
        }
   }

    window.onbeforeunload = function() {
        setTimeout(function() {
            window.onbeforeunload = function() {};
            setTimeout(function() {
                document.location.href = __redirect_to;
            }, 500);
        },5);
        return 'WAIT BEFORE YOU GO! CLICK THE *Stay on this page* BUTTON RIGHT NOW! I HAVE SOMETHING VERY SPECIAL FOR YOU COMPLETELY FREE.';
    }
    }, 500);
})();
</script>

jQuery selector after dom change

in jQuery some time we can’t get default event[selector] as like “click”,”change”,’focus’ etc. So in bellow snippet we can easily bind event.


/******/
/* Syntax of jquery selector.
/******/
jQuery(selector).live(events, data, handler);                // jQuery 1.3+  
jQuery(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+  
jQuery(document).on(events, selector, data, handler);        // jQuery 1.7+  


/******/
/* jQuery default selector.
/******/
jQuery('.btnAction').click(function(){
	// Do something
});


/******/ 
/* Dynamic content load after some time not bind default jQuery event thane after used those three events.
/******/
jQuery(document).delegate('.btnAction','click',function(e){
	// Do something
});

// jQuery 1.3+  
jQuery('.btnAction').live('click',function(){
	// Do something
});

// jQuery 1.7+  
jQuery('.btnAction').on('click',function(){
	// Do something
});

jQuery(document).on('click',".btnAction", function(){
	// Do something
});

jQuery multiple event for same time

If this was the same collection of elements you could user as like this

jQuery('#myid').bind('blur keypress',function(e) {		
		
		if(e.keyCode==27){
			jQuery(this).closest('tr').slideUp('fast');			
		}
		else if(e.type == 'blur'){
			if(jQuery(this).closest('tr').css('display') != 'none')
			{
				jQuery('#mytriggerid').trigger('click');	
			}
		}
		
	});