Javascript: Error in custom script for lazyload images - javascript

I am trying to write the following script to lazyload background images of sub-menu on a website. But this function returns the error
Missing ) after argument list
My requirement is to load the background images after the window loaded completely. What i am doing is , I have added some data attributes to get the background image url, position etc. and then on windows load call this function which adds the css for the sub-menu.
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
imgDefer[i].css(
"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
);
console.log(imgDefer[i].getAttribute('data-background-image'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
console logs returns the url of image:
url(image/sub_menu_image.jpg)
How can i fix this problem?
Update:
This is the final solution for my problem. I hope it may help someone
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
$(imgDefer[i]).css("background-image",imgDefer[i].getAttribute('data-background-image'));
$(imgDefer[i]).css("background-position",imgDefer[i].getAttribute('data-background-position'));
$(imgDefer[i]).css("background-repeat",imgDefer[i].getAttribute('data-background-repeat'));
}
}
}
window.onload = menuImageLazyLoad;
</script>

I guess you miss {}
For multiple attribute css settings,
It should be set as an object https://www.w3schools.com/jquery/jquery_css.asp
imgDefer[i].css(
{"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
});

Related

Custom Link - Individual URL Links per Image - Elementor Gallery

I use the following code to Add Individual URL Links per Image in elementor
if I have several galleries on the same page, how can it be indicated that it refers to a specific e-gallery-item, or what parameter needs to be changed in the code?
The post number or something else? What code do I need instead?
`<style>.e-gallery-item{cursor: pointer;} </style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('.e-gallery-item');
var links = [
'https://www.domain-name.com/1',
'https://www.domain-name.com/2',
'https://www.domain-name.com/3'
];
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});
</script>`

2 functions init inside one JS

I try to combine 2 defer functions init to 1 Java script.
I actually try now combine another one but he make conflict and the JS very heavy. this is 2 different script + 1 is not so important (but if you guys succeed help me combine all of them perfectly is be better).
This the code I try put after I edit him 2( 2 functions init ):
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
I make him a short too... he defers the images but slower the site:
function init(){for(var t=document.querySelectorAll("div[data-src]"),e=0;e<t.length;e++)t[e].setAttribute("style","background-image: url({url})".replace("{url}",t[e].getAttribute("data-src")));t=document.getElementsByTagName("img");for(e=0;e<t.length;e++)t[e].getAttribute("data-src")&&t[e].setAttribute("src",t[e].getAttribute("data-src"))}window.onload=init;
(you can look the code is deferred on the website: locksmithunit.com)
but he very slow on the page load.
and this all the original codes... these codes are for deferring images
and the last one is for "frame"
the frame not so important. and if you can give me him separately because
have pages I don't have iframe.
please help me guys, i very lost.
I most combine at least the first 2 scripts from all the 3 I send now:
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
<script>
<script>
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
}
window.onload = init;
</script>
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
ok. so I try to defer images on my website... on 120 pages...
now, when i start, i was able to defer only images.
after that, I succeed defer the background-image: url().
but it is different JS as you see on the example I post before.
I succeed combine them but still, the JS no give full power.
after that, I start to fix again pages and i notice have google maps iframe
in couple of pages. ( something like 40 pages).
and I try to defer the iframe as well but it was too much for the javascript and the website loses the page load...
the JS needs to rewriting again...
i try a couple of variations as I post before, but none of them really improve the page load.
if we sucssed fix the Javascript at least put the 2 functions inside JS, JS of the background and images you will save me because I already edit all the 120 pages and the JS work and defer, but damage the page load because the JS is not written well.
(iframe is not so important like the images and the background)

How to apply .css rules on dynamic html elements generated in javascript

I've read similar questions and tried several suggestions nothing had worked - hope you can help
Scenario:
loading my website with initial (static) index.html -- looks great css takes fine
clicking on "next page" button --> retrieves successfully the data from DB and dynamically generates the element's innerHTML section.
Problem: the audio player is the only element which doesn't look the same
Initial state: when loading the site first time
and how it looks after generating the HTML
All other tags like header image and text do apply the css rules.
The audio player has rules in the css file and has also the following script at the end of index.html and I'm suspecting thats the root of my problem not being "fired/called" again for the new generated elements
<script>
document.addEventListener('DOMContentLoaded', function() {
var mediaElements = document.querySelectorAll('video, audio'), total = mediaElements.length;
for (var i = 0; i < total; i++) {
new MediaElementPlayer(mediaElements[i], {
pluginPath: 'https://cdn.jsdelivr.net/npm/mediaelement#4.2.7/build/',
shimScriptAccess: 'always',
success: function () {
var target = document.body.querySelectorAll('.player'), targetTotal = target.length;
for (var j = 0; j < targetTotal; j++) {
target[j].style.visibility = 'visible';
}
}
});
}
});
</script>
If that's the reason how can I invoke this event on demand and how can I do it from the javascript file?

Javascript modification of CSS class url change for background image

I am trying to get a background image to change based on a setting in the database, for right now I'm just trying to get a a way of simply modifying the image used without using the data base but I'm hitting a snag. Without the javascript the image appears fine, with the javascript it is simply not there; leading me to believe there is an issue finding the path written to the css.
Thanks in advance for any help!
<script type="text/javascript" language="javascript">
function changecss(myclass, element) {
var CSSRules
var link1 = "url('../../graphics/MainMenuBG0.gif')";
var link2 = "url('../../graphics/MainMenuBG1.gif')";
if (document.all) {
CSSRules = 'rules';
}
else if (document.getElementById) {
CSSRules = 'cssRules';
}
for (var i = 0; i < document.styleSheets[0][CSSRules].length; i++) {
if (document.styleSheets[0][CSSRules][i].selectorText == myclass) {
if (document.styleSheets[0][CSSRules][i].style[element] == link1) {
document.styleSheets[0][CSSRules][i].style[element] = link2;
} else {
document.styleSheets[0][CSSRules][i].style[element] = link1;
}
}
}
}
</script>
You should try something like this :
if (document.styleSheets[0][CSSRules][i].style.getProperty('background-image') == link1) {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link2);
} else {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link1);
}

Javascript - swap image on click or rollover

I know how to do this in jquery but i am trying to do the below in pure old school javascript. Can someone help:
$(".thumbnail").click(function() {
$("#mainImage").attr("src", $(this).attr("src"));
});
My ultimate goal is to click on a thumbnail and have the main image change but I need to do it in javascript (no jquery). I know this sounds pretty simple but I cannot figure it out. thank you.
There are so many things that jQuery gives you automatically that it's difficult to give you an answer that will do everything that your jQuery code does. Here is a simple example that will find every image with a class of thumbnail and set its onclick property to an event handler that performs an image swap.
onload = function () {
var bigImg = document.getElementById("mainImage");
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (/\bthumbnail\b/.test(img.className) {
img.onclick = thumbnailHandler;
}
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
If you don't have to support IE7, you can simplify it slightly by using document.querySelectorAll():
onload = function () {
var bigImg = document.getElementById("mainImage");
var thumbs = document.querySelectorAll(".thumbnail");
for (var i = 0; i < thumbs.length; i++) {
thumbs[i].onclick = thumbnailHandler;
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
As an aside, I don't understand why you are setting the source of the main image to be the source of the thumbnail. Are you loading the full image into the thumbnail? That can be a lot to download and can quickly increase the memory footprint of your page.
Event delegation is probably the easiest way:
function expandThumbnail(e) {
if(~(' ' + e.target.className + ' ').indexOf(' thumbnail ')) {
document.getElementById('mainImage').src = e.target.src;
}
}
if(document.addEventListener) {
document.addEventListener('click', expandThumbnail, false);
} else {
document.attachEvent('onclick', function() {
expandThumbnail({
target: event.srcElement
});
});
}
If I understand right, you have a thumbnail image displayed, let's say '1thumb.png', of an associated image, let's say '1.png', and when you click this thumbnail image you want to change the src attribute of a main image, let's say with id='mainimg', to show the '1.png' image associated to the thumbnail instead of whatever it's showing. I tried this and it works:
Inside your <header>:
<script type='text/javascript'>
function myHandler(source){
document.getElementById('mainimg').src=source;
}
</script>
...
Your thumbnail code:
<img src='1thumb.png' onclick="myHandler('1.png')"/>
or, for rollover triggering:
<img src='1thumb.png' onmouseover="myHandler('1.png')"/>
Check it out: http://jsfiddle.net/d7Q27/7/

Categories

Resources