Category: jQuery

Play Pause Vimeo or YouTube multiple video JavaScript

have found a solution to starting/pausing multiple Vimeo and YouTube videos from separate buttons

YouTube


<a href="javascript:void callPlayer(&quot;whateverID&quot;,&quot;playVideo&quot;)">Start</a> &bull; <a href="javascript:void callPlayer(&quot;whateverID&quot;,&quot;pauseVideo&quot;)">Pause</a> &bull; <a href="javascript:void callPlayer(&quot;whateverID&quot;,&quot;stopVideo&quot;)">Stop</a> - Hover over the links to see the called function




<div id="whateverID"><iframe width="640" height="390" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe></div>




<a href="javascript:void callPlayer(&quot;whateverID1&quot;,&quot;playVideo&quot;)">Start</a> &bull; <a href="javascript:void callPlayer(&quot;whateverID1&quot;,&quot;pauseVideo&quot;)">Pause</a> &bull; <a href="javascript:void callPlayer(&quot;whateverID1&quot;,&quot;stopVideo&quot;)">Stop</a> - Hover over the links to see the called function




<div id="whateverID1"><iframe width="640" height="390" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/AkwVg9viC-g?enablejsapi=1"></iframe></div>




function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
if (iframe) {
// Frame exists,
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
}

Vimeo

Single video (simpler) version here: <a href="https://codepen.io/filipbech/pen/cbaxq">https://codepen.io/filipbech/pen/cbaxq</a>


<iframe width="560" height="315" src="//player.vimeo.com/video/5705212?api=1&player_id=video1" id="video1"></iframe>
<button class="play" data-id="video1">Play</button>
<button class="pause" data-id="video1">Pause</button>



<iframe width="560" height="315" src="//player.vimeo.com/video/5705212?api=1&player_id=video2" id="video2"></iframe>
<button class="play" data-id="video2">Play</button>
<button class="pause" data-id="video2">Pause</button>




Red background means "playing"... 
<i>(try clicking either "native" or "custom" controls, to see that both work as expected)</i>

/* Grabbing objects to play with */
var playButtons = $('.play'),
    pauseButtons = $('.pause');

/* Helper function to send a message to Vimeo-iframe */
function vimeoPost(action, value, target) {
	var data = { method: action };
	if (value) {
		data.value = value;
	}
	target.contentWindow.postMessage(JSON.stringify(data), '*');
};

/* When clicking the playButton, send a "play"-message to given iframe*/
playButtons.click(function() {
  var iframe = document.getElementById(this.dataset.id);
  vimeoPost('play',null,iframe);
});

/* When clicking the pauseButton, send a "pause"-message to given iframe */
pauseButtons.click(function() {
  var iframe = document.getElementById(this.dataset.id);
  vimeoPost('pause',null,iframe);
});

/* When a message is received, deal with it */
window.addEventListener('message', function(event) {
  /* Get message and sender from the event */
  var message = JSON.parse(event.data);
  var sender = document.getElementById(message.player_id);
 
  /* If the message.event is "ready", then send a message to add eventlisteners for play and pause also */
  if(message.event == "ready") {
 	vimeoPost('addEventListener','play',sender);
   vimeoPost('addEventListener','pause',sender);
  }
  
  /* Because of the above, we will start receiving events when video is played or paused - we will toggle a class, just to show it visually */ 
  if(message.event == 'play') {
		sender.classList.add('playing');    
  }
  if(message.event == 'pause') {
    sender.classList.remove('playing');
  }
  
}, false);

YouTube Vimeo

Advertisements

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

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