Tag: 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

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

}

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

How add custom css and jquery in wordpress

How add custom css and jquery in wordpress

This code put in functions.php and set path as folder.

/**
* Enqueue scripts and styles for the front end.
*/
function your_function_scripts() {
wp_enqueue_style('style', get_template_directory_uri() . '/style.css', '', '1.0');
wp_enqueue_style('bootstrap_theme_mini', get_template_directory_uri() . '/css/bootstrap.css', '', '1.0');
wp_enqueue_style('theme_mini', get_template_directory_uri() . '/css/theme.css', '', '1.0');

wp_enqueue_script( 'jquery_min','//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js', 0 );
wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array('jquery'), '1.0', 0 );
}
add_action( 'wp_enqueue_scripts', 'your_function_scripts' );

Above snippet using to we add custom CSS and jQuery in Front end.

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