lozad.js icon indicating copy to clipboard operation
lozad.js copied to clipboard

How to adjust this script for background image lazy load?

Open BeholdPL opened this issue 5 years ago • 1 comments

I have this little script:

<?php 	
	echo '
	<script>
	// random
	function randomImage(){
	  var images =[';
		$images = get_field('header-images');
		if( $images ): foreach( $images as $image ):
				$arr = $image['url'];
				echo json_encode($arr).",";
        	endforeach;
	endif;	  
	echo '];
 var size = images.length;
	var x = Math.floor(size * Math.random());
	console.log(x);
	var element = document.getElementsByClassName("l-header-image");
	console.log(element);
	element[0].style["background-image"] = "url("+ images[x] + ")";
	}
	document.addEventListener("DOMContentLoaded", randomImage);
	</script>';
	?>

What this script do is loading background-image from array for div class "l-header-image lozad" with each page reload. The array is ACF gallery field.

So I need adjust this script for lozad background-image option :)

Any ideas? :)

BeholdPL avatar Feb 26 '19 23:02 BeholdPL

You need to change

element[0].style["background-image"] = "url("+ images[x] + ")";

to

element[0].setAttribute("data-background-image", images[x]);

haywirephoenix avatar Feb 21 '20 19:02 haywirephoenix