Category: jQuery

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');	
			}
		}
		
	});

Page loader jquery

Page loader to use all data load first after display the details.

Put This JS Code in js file or page header

$(window).load(function() {

$(“.loader”).fadeOut(“slow”);

})

Put This Code CSS file

<style>

.loader {

position: fixed;

left: 0px;

top: 0px;

width: 100%;

height: 100%;

z-index: 9999;

background: url(‘/wp-content/themes/bluedomus-git/include/England/tpl/page-loader.gif’) 50% 50% no-repeat rgb(249,249,249);

}

Put This Code Html Page