How to apply .css rules on dynamic html elements generated in javascript - 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?

Related

Javascript: Error in custom script for lazyload images

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

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)

Reload a content almost invisibly and no blinking effect using JAVASCRIPT

I'm writing a small progam wherein I'm getting data using $.get then display the data so far so good and then there's this part then when I click a certain link it refresh the page but it has this blinking effect. Is there a way on how to reload the content get the new updated content then replace the previously loaded data.
NOTE: I didn't use setInterval or setTimeout function because it slows down the process of my website. any answer that does not include those functions are really appreciated.
Here's the code
function EmployeeIssues(){
$('#initial_left').css({'display' : 'none'});
var table = $('#table_er');
$.get('admin/emp_with_issues', function(result){
var record = $.parseJSON(result);
var data = record.data,
employees = data.employees,
pages = data.pages;
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
}else{
$('#er_tab_label').html('<b>No employees with issues yet.</b>');
}
});
table.html('');
}
then this part calls the function and display another updated content
$('#refresh_btn').on('click', function(e){
e.preventDefault();
var tab = $('#tab').val();
if(tab == 'er'){
EmployeeIssues();
}
});
What should I do to display the content without any blinking effect?
thanks :-)
This section might be the issue :
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
} else ...
It seems you're asking table_er to fade in once per run of the loop whereas s there can only be one such table, you only need to do it once ?
first try re-arringing it like this:
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
table.append(write_link(employees[i])); // function that displays the data
}
$('#table_er').fadeIn('slow'); // only do this after the table has all its html
if(pages){
$('#pagination').html(pages);
}
} else ....
Another possibility is that you're running through a loop and asking jquery to do stuff while the loop is running. It might be better to work out the whole HTML for the new page data in a string and then get the screen to render it in one line. I cna't do this for you as I don't know what's in write_link etc but something like this ..
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
var sHTML ="";
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
sHTML+=write_link(employees[i]); // maybe this is right ? if write_link returns an HTML string ?
}
table.append(sHTML); // add the HTML from the string in one go - stops the page rendering while the code is running
$('#table_er').fadeIn('slow'); // now show the table.
if(pages){
$('#pagination').html(pages);
}
} else ...

Placing elements within a container div into an array - jQuery or JavaScript

I have a div that contains a number of Instagram images, produced by the instafeed.js plugin. After running the plugin, the resultant HTML looks like this:
<div id="instafeed">
<a><img /></a>
<a><img /></a>
<a><img /></a>
etc...
</div>
I am trying to find a way to load the contents of this div into an array; I believe that the easiest way would be to just take the tags, which is fine.
I'm pretty inexperienced with both JS and jQuery, which is why I'm having difficulty achieving this and I've not been able to find any forum posts that quite do what I'm hoping to achieve.
So far, all I'm trying to do is load the contents of the div into an array and print it back out to the document, which should (in my mind anyway) add the tags back into the HTML. I'm trying with both JavaScript and jQuery and having little success with either. I'd appreciate any thoughts:
JS:
var containerDiv = document.getElementById('instafeed');
var pics = containerDiv.getElementsByTagName('img');
console.log(pics); //Tells me at least that I have an array of img
for (var i = 0; i < pics.length; i++) {
document.write(pics[i]);
} //Seemingly does nothing
jQuery:
(I'm really sorry if this code is just all wrong, I really don't know jQuery very well at all)
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
console.log(pics[i]);
}
});
Any thoughts, tips or pointers would be much appreciated.
Edit:
Just to add a little background to my problem, to avoid causing any more confusion.
I'm trying to pull four random images from a user-specific Instagram feed for display on a website. instafeed.js can pull just four images and it can randomise the images, but Instagram itself always sends the four most recent images, so the plugin is just randomising the order of the same four pictures each time.
I'm trying to let the plugin send through every picture, which will go into the div instafeed. From here I want to load all of the contained images into an array so that I can randomly pick four images for display on the site.
JQuery code that you write is correct. Only you need the div where you need to put the images.
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
$('div#yourDiv').append(pics[i]);
}
});
See the line of the for()
You can extract only the SRC of the images and then make like you want
$('#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
console.log(pics); // returns an array of src.
Thank you to everyone who has tried to help me along with this. It turns out that the problem I was having stemmed from my query attempting to run before instafeed.js had been able to pull the images through from Instagram, and so there was nothing for it to find in the div. I've managed to fix this with a setTimeout.
For anyone who is interested, and just in case anyone else might come across this in future with a similar problem, here is my complete code (it's a little inelegant I'm sure, but I'm still a relative novice at JS.)
function snagImages() {
var pics = [];
$('div#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
reduceGallery(4, pics);
}
function reduceGallery(limit, pics) {
if (limit === undefined) {
limit = 4;
}
var gallery = [];
while (gallery.length < limit) {
var j = Math.floor(Math.random() * pics.length);
if ( gallery.indexOf(pics[j]) > -1) {
continue;
}
gallery.push(pics[j]);
}
displayPics(gallery);
}
function displayPics(gallery) {
for (var i = 0; i < gallery.length; i++) {
document.getElementById('gallery').innerHTML += '' + '<img src="' + gallery[i] + '" alt="Gallery Image" />' + '';
}
}
var userFeed = new Instafeed( {
options
});
userFeed.run();
setTimeout(function() { snagImages() }, 500);

Loop through all images and change size?

The script below works for posts that are already on the page. But, when I click on load more posts, the new posts that get added to the page don't change the source of the image so that they are blurry.
Is there a way to loop through all images and change the src of it, even the ones that are not shown?
function resizeThumb(size) {
var popularPost = document.getElementById('Blog1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s72\-c/g, "\/s" + size + "-c");
image[i].width = size;
image[i].height = size;
}
}
// Resize to 200 × 200
resizeThumb(200);
Yes. Basically locate the button that loads more, find it's name.
If your button looks like this:
Load more
Put this before it so it looks like this:
<span onclick="resizeThumb(200); ">
Load more
</span>
It's the lousiest solution but the question is lousy too.

Categories

Resources