How to lazy load videos with jquery or javascript - javascript

So I am trying to the load a embed video after a image(Splash-Imag) is clicked. The Delay should be 1.5 Seconds
<div id="mv-info">
<div id="content-embed" style="<?php $splash = info_movie_get_meta('fondo_player'); if(empty($splash)) { echo 'display:block;';}?>">
<div class="mplay">
<?php if (get_sub_field('type_player') == "p_iframe") {?>
<?php if($dato = get_sub_field('embed_player')) { ?>
<iframe src="<?php echo $dato; ?>" frameborder="0" allowfullscreen></iframe>
<?php }?>
</div>
Here $dato is the embed URL, Once I click the splash-image(class) in div class mvi-info the splash image goes and video pops out. But what i want to do is delay the video for 1.5 seconds or less so that it doesn't hinder my page speed.
I used this code but it doesn't seem to work
<script type="application/javascript">
$('.mvi-cover').click(function(){
var iframe = $('.mplay iframe').each(function(item){
var src= $(this).data('src');
$(this).attr("src",src);
});
$( ".splash-image" ).fadeOut(function(){
$( ".splash-image" ).remove()
});
$('#content-embed').fadeIn();
})
</script>
If anyone can help me then I will be really grateful.

You could use some jQuery objects to load the iframes without appending them to DOM. And using a timeout, you could do this 1,5 second after the page has finished loading.
Then, on a click event, change the src attribute of the iframe next to the clicked splash image (not all). Since the browser already has loaded the content, it will be instantanous.
I am pretty sure you have many iframes like this because you use a PHP loop. DO NOT use id in that kind of loop that produces HTML. It ends up in multiple time the same id. Use classes instead.
Try that to load the iframes 1.5 sec after page load:
$(document).ready(function () {
let iframes = $(".mplay iframe");
setTimeout(function () {
iframes.each(function (index) {
console.log(`Looping through iframes... #${index+1}`)
// Create a temporary jQuery object just to load
let temp = $("<iframe>")[0];
temp.src = $(this).data("src");
// Make sure the content gets loaded
temp.on("load", ()=> console.log(`The content of Iframe #${index+1} is loaded... The url was ${$(this).data("src")}`) )
});
},1500);
});
And this to handle the click events on the splash images:
$(".mvi-cover").click(function () {
let src = $(this).data("src");
$(this).attr("src", src);
let embed = $(this).next(".content-embed");
$(this).fadeOut(function () {
$(this).remove();
embed.fadeIn();
});
});
I am not 100% sure of your rendered HTML structure... But you get the idea.

Try this:
<div id="mv-info">
<?php if($splash = info_movie_get_meta('fondo_player')) {?><a title="<?php the_title(); ?>" class="thumb mvi-cover splash-image" style="background-image: url(<?php echo $splash;?>)"></a><?php }?>
<?php }?>
<div id="content-embed" style="<?php $splash = info_movie_get_meta('fondo_player'); if(empty($splash)) { echo 'display:block;';}?>">
<div class="mplay">
<?php if (get_sub_field('type_player') == "p_iframe") {?>
<?php if($dato = get_sub_field('embed_player')) { ?>
<iframe data-src="<?php echo $dato; ?>" frameborder="0" allowfullscreen></iframe>
<?php }?>
</div>
<script type="application/javascript">
$('.mvi-cover').click(function(){
var iframe = $('.mplay iframe').each(function(item){
var src= $(this).data('src');
$(this).attr("src",src);
});
$( ".splash-image" ).fadeOut(function(){
$( ".splash-image" ).remove()
});
$('#content-embed').fadeIn();
})
</script>

This code works fine for delay for one source. But not able to get it right for multiple sources.
<div class="mplay">
<?php if (get_sub_field('type_player') == "p_iframe") {?>
<?php if($dato = get_sub_field('embed_player')) { ?>
<script>
window.setTimeout(function () {
var iframe = document.getElementById('myIframe');
iframe.setAttribute('src', '<?php echo $dato;?>');
}, 1500);
</script>
<iframe id="myIframe" src="" frameborder="0" allowfullscreen></iframe>
<?php }?>

Related

more than one slideToggle in page

I have a simple code with slideToggle function that is working fine in 4 divs, it opens hidden content all at the same time in this Divs.
It changes the image when clicked, but only the first one, not the rest, how can i do it for all?
this is the code for the 4 buttons repeats equaly, it opens all, but wont change image in all:
<div class="show" style="display:none"><h1>THE TEXT TO APPEAR</h1></div>
<img id="bg" class="loadMore" src="<?php echo get_template_directory_uri(); ?>/img/masGris.svg" />
$(document).ready(function() {
$('.loadMore').click(function() {
$('.show').slideToggle('1100');
var src = $("#bg").attr('src') == "<?php echo get_template_directory_uri(); ?>/img/less.svg" ? "<?php echo get_template_directory_uri(); ?>/img/masGris.svg" : "<?php echo get_template_directory_uri(); ?>/img/less.svg";
$("#bg").attr('src', src);
return false;
});
});
Change the $("#bg") of selector with $(this) .because id is unique one.for all image try with each()
updated
$(document).ready(function() {
$('.loadMore').click(function() {
$('.show').slideToggle('1100');
$('.loadMore').each(function(){
var src = $(this).attr('src') == "<?php echo get_template_directory_uri(); ?>/img/less.svg" ? "<?php echo get_template_directory_uri(); ?>/img/masGris.svg" : "<?php echo get_template_directory_uri(); ?>/img/less.svg";
$(this).attr('src', src);
})
return false;
});
});
This only changes the icon that i clicked in. What about to change it all images, no matther with one i click? someone?

Javascript gets only the first id from a foreach loop. Why?

I use a foreach loop to get some tabs with different id's. This way I get tabs with ids tab1, tab2, tab3, etc. Than, when I want to get the id of each tab using javascript, it returns only the id of the first tab and uses this for all tabs. It does not loop as php do. Why?
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div id="divid" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var dividvalue = document.getElementById('divid').innerHTML;
alert(dividvalue);
});
</script>
<?php
}
?>
Change the id in your HTML to class, and use getElementsByClassName instead of getElementById your in JavaScript.
Your div:
<div class="divid"> <!-- etc -->
and your JS..
var dividvalue = document.getElementsByClassName('divid')[0].innerHTML;
Also consider changing divid to divclass for consistency's sake.
Full edited code:
<script>
var i = 0;
</script>
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div class="divclass" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var divclassvalue = document.getElementsByClassName('divclass')[i].innerHTML;
alert(divclassvalue);
i++;
});
</script>
<?php
}
?>

Why is jQuery(document).ready not working? / How do I add CSS to an element in jQuery?

I'm new to jQuery and I'm having problem with a piece of code.
I'm trying to add Image Power Zoomer v1.2 to my website, which works on the main image, but not the rollover image! The rollover image changes, but power zoomer only shows the loading image.
This is an example URL: Example1
This is my code:
<script type="text/javascript">
var bufferImage = new Array();
function Buffer(filename) {
var i = bufferImage.length;
bufferImage[i] = new Image();
bufferImage[i].src = filename;
}
function showImage(filename) {
document.images[Image_Name].src = filename;
}
Image_Name = "image_pal";
Buffer("thumbnail.php?pic=<? echo $image_pal['media_url'];? >&w=600&sq=Y");
jQuery(document).ready(function($){ //fire on DOM ready
$('#myimage').addpowerzoom({
powerrange: [2,8],
largeimage: null,
magnifiersize: [200,200] //<--no comma following last option!
})
})
</script>
<? $sql_image_pal=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");
$image_pal=$db->fetch_array($sql_image_pal);
$sql_image=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");?>
<div align="center" class="image_pal">
<? if (empty($image_pal['media_url'])) {?>
<img src="themes/<?=$setts['default_theme'];?>/img/system/noimg.gif" name="image_pal" width="600" />
<? } else {?>
<img id="myimage" src="thumbnail.php?pic=<?=$image_pal['media_url'];?>&w=600&sq=N" border="0" alt="<?=$item_details['name'];?>" name="image_pal" />
<? }?>
</div>
<div class="list_carousel_img" align="center">
<ul id="small_img">
<? while($image=mysql_fetch_array($sql_image)){?>
<? $ad_img=$image['media_url'];?>
<li class="small_img">
<a href="thumbnail.php?pic=<? echo $ad_img;?>" onmouseover="showImage('thumbnail.php?pic=<?=$image['media_url'];?>&w=600&sq=Y')"class="lightbox" rel="thumbnail_images" ><img src="thumbnail.php?pic=<?=$image['media_url'];?>&w=60&sq=Y" border="0" alt="<?=$item_details['name'];?>"/></a>
</li>
<? } ?>
</ul>
<div class="clearfix"></div>
<a id="prev_img" class="prev_img" href="#"></a>
<a id="next_img" class="next_img" href="#"></a>
<? if ($setts['lfb_enabled'] && $setts['lfb_auction']) { ?>
<div><img src="themes/<?=$setts['default_theme'];?>/img/pixel.gif" width="1" height="5"></div>
<? include("scripts/scroller/show_rep_details.php"); ?>
<? } ?>
I'm having trouble with jQuery Selectors. I have looked all over the web, spent many hours, but with no joy.
This is the site i got the Image Power Zoomer v1.2 from:
dynamicdrive.com
Question #2
Like i said im a newbie but i think my problems here jQuery selector these are some examples but i do not know what i need to add from my code
<script type="text/javascript">
jQuery(document).ready(function($){ //fire on DOM ready
$('img.showcase').addpowerzoom() //add zoom effect to images with CSS class "showcase"
$('#gallerydiv img').addpowerzoom() //add zoom effect to all images inside DIV with ID "gallerydiv"
})
</script>
What do i need to add here
$('????????????').addpowerzoom()
Thanks For all your help
jQuery(document).ready(function($){ //fire on DOM ready
==>
$(document).ready(function(){ //fire on DOM ready
Unless you changed your jQuery selector, this is the default
Because you asked another question in the answers (and even got an upvote?)
What do i need to add here
$('????????????').addpowerzoom()
This is my answer to that question:
$("img").each(function(){
$(this).addpowerzoom();
});
like in this demo: http://jsfiddle.net/u7w0ppq9/ with adding class instead of powerzoom (I do not have that library so, but it's basically the same)

Button to reload the contents of a div which contains php

I have a div containing php that loads a random image from a directory. This bit works fine when i reload the page. The code:
<div id="imageArea">
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
</div>
And further down the page i have another div that contains a button. I want it so that when people click this button it loads a new random image, i guess it would reload the div, but i don't want it to reload the page, is that possible? The button:
<div id="newPic">
<input type="button" value="Reload" id="Reload"/>
</div>
I have tried:
<script>
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html("result reloaded successfully");
});
});
</script>
and:
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html(ajax_load).load(loadUrl);
});
});
I am new to php and javascript and so i have been following other peoples instructions.
Thank you
split your php script to another file (just echo the img tag), and then use ajax to call that page.
$("#reload").click(function(){
$.ajax({
url:"demo.php",success:function(ajax_load){
$("#imageArea").html(ajax_load)
}});
});
php file
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
have you tried to use ajax to update the div with the image?
here's the code
$(document).ready(function(){
$('#clickme').click(function(){
var number = 1 + Math.floor(Math.random() * 10);
$('#contentimg').attr('src','0'+number+'.jpg');
});
});
this would work given that the images are in the same folder else give the src of image accordingly

Ajax WordPress post popup with SimpleModal and jQuery

I tried to implement this mode here http://wordpressthemescollection.com/ajax-wordpress-post-popup-with-simplemodal-and-jquery-488.html but nothing seems to work.
This is what I do.
1 / Include in header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo("template_url"); ?>/js/jquery.simplemodal.js"></script>`
The links are goods cause I checked them both.
2 / Include in header this script
<script>
jQuery(document).ready(function() {
jQuery('a.postpopup').live('click', function(){
var id = jQuery(this).attr('rel');
jQuery('<div id="ajax-popup"></div>').hide().appendTo('body').load('<?php bloginfo('url')?>/ajax/?id='+id).modal({
opacity:90,
position: ["0%"],
overlayClose:true
});
return false;
});
});
</script>
3 / Make a custom template with this code
<?php
/*
Template Name: Ajax
*/
?>
<?php
$post = get_post($_GET['id']);
?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<div class="whatever">
<h2 class="entry-title"><?php the_title() ?></h2>
<div class="entry-content">
<?php the_content(); ?>
</div>
</div>
<?php endif; ?>
And after that made a page named Ajax and assign the template Ajax.
4 / Implement a link
this link
If i click on the link nothing happens.
What did I do wrong cause I did not have a clue about it?
Thanks.
jQuery .load() is ajax and so you need to do any subsequent things in a callback like this:
var $ajax-div = jQuery('<div id="ajax-popup"></div>').hide().appendTo('body');
var url = '<?php bloginfo('url')?>/ajax/?id=' + id;
$ajax-div.load(url), function() {
// the callback
jQuery('#ajax-popup').modal({
opacity: 90,
position: ["0%"],
overlayClose:true
});
});
when you create an new post or page content on wordpress admin, select the "Ajax" template for your page

Categories

Resources