How to replace image src after page load in jQuery - javascript

How can change a specific part of an image src using jQuery after the page is being loaded?
This is an example link,
<img src="https://example.com/73832d3c5fca_175x175_c0b~bn1v1.jpg">
I want to replace the b1n1v1 with bn1v1 after the page is being fully rendered.
This is what I have tried to do so far but it doesn't work.
$(document).ready(function() {
return $(this).text().replace("b1n1v1", "bn1v1");
});
Thank you!

Loop each images and replace the same .attr('src')
$(document).ready(function() {
$('img').each(function(){
$(this).attr('src',$(this).attr('src').replace("b1n1v1", "bn1v1"));
});
});
each https://api.jquery.com/each/

Your syntax isn't quite right as this refers to the window and return is redundant at that point.
To make this work for all img elements in the page you need to loop through them. To do that you can provide a function to attr() which accepts the current value as an argument and returns the new value. Try this:
$(document).ready(function() {
$('img').attr('src', function(i, s) {
return s.replace("b1n1v1", "bn1v1");
});
});

Add a class to that image imageClass.
$('.imageClass').attr('src').replace('bn1nv1', 'bn1v1');

Related

Update IMG SRC value with the .load() return with jQuery

The following puts whatever I echo in whatever.php into the myDiv div, and it's fine.
$('#myDiv').load('whatever.php');
If I do
document.getElementById(id).src = 'newpic.jpg';
If id points to a valid IMG, it will replace the picture, and it's fine.
Now, how can I put the output of the load into an IMG SRC?
I tried both, and both are not working:
$('#'+id).src.load('whatever.php');
or
document.getElementById(id).src = $('#hiddenDiv').load('whatever.php');
Thank you
You can try to load data and append it to the <div> tag first. Then, appending that tag to the body (some element else).
BTW, you can catch event DOMNodeInserted. This event is used to catch when some element is inserted to the DOM.
In this example, when the div is ready to use, we add image source inside <img> tag.
$(document).on('DOMNodeInserted', '#myDiv', function () {
$('img').prop('src', 'https://www.peta.org/wp-content/uploads/2018/05/tiger.jpg');
});
setTimeout(function () {
var div = $('<div id="myDiv">');
div.append('<img width="100" height="100">');
div.appendTo('body');
},2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thanks to #AlwaysHelping I realized I didn't need the "load" function, but a simple Ajax call:
$.ajax('whatever.php')
.done(function(data) {
document.getElementById(id).src = data;
})
I think I have been caught in (ab)using the load function too often, forgetting that a simple Ajax call could represent the simplest solution

Javascript / jQuery: Why do I keep getting undefined?

I have the following html code:
<a class="tabTitle" id="title_boxtab_default" tab-type="default" href="#tabs-3">Sample</a>
In jQuery I'm trying to get the value of the href attribute with:
$('.tabTitle').last().attr('href');
But it keeps telling me it's undefined?
I should mention that the number of links with class"tabTitle" increases. That's why I use .last()
Works just fine for me in JSFiddle. I changed it to this, and it returned #tabs-3:
alert($('.tabTitle').last().attr('href'));
My guess is that it's not running from a ready handler like this:
$(function() {
var x = $('.tabTitle').last().attr('href');
});
It should work. Make sure you are running the script when the element is present in the DOM, f.ex using .ready():
$(function() {
alert( $('.tabTitle').last().attr('href') );
});
DEMO: http://jsbin.com/IyeSacU/1/edit
Try DOM Ready
$(document).ready(function(){
$('.tabTitle').last().attr('href');
});
Fiddle

onload for div tag

I have div tag, after some event, I insert (change old content) into this tag, several images and also texts, for example:
$("#some_button").on("click", function () {
$("#mydiv").html("<div>aaaa</div><img src='1.jpg'><div>bbb</div><img src='2.jpg'>");
});
I want, that after load "mydiv" tag full content, alert("mydiv contonet is loaded"). That is, some like this:
$("#mydiv").onload( function () {
alert("mydiv contonet is loaded");
});
Tell please, how can this make?
Divs have no onload event. The best you can do is something like this:
<div id="myDiv">I am a div</div>
<script>// do stuff with loaded div</script>
...unless you can/want to specifically address stuff within the div which does support onload, like images.
.html() is a synchronous operation. The actual updating of the DOM depends on what your html content is. If you have <img> or <iframe> tags, they will take time to load. The next statement following the .html() should immediately see the new html contents.
You can have a callback using .load()
http://api.jquery.com/load/
Preload (http://stackoverflow.com/questions/476679/preloading-images-with-jquery) your images then you won't have to worry about this use case.
You'll have to check the loading of the images you have in your div as there is no callback usable in your case.
The typical way is, for each image
to check if the image is loaded (check if (img.width))
add a onload callback on this image
As you have multiple images, you might want a function like this one :
function onLoadAll(images, callback) {
var n=0;
for (var i=images.length; i-->0;) {
if (images[i].width==0) {
n++;
images[i].onload=function(){
if (--n==0) callback();
};
}
}
if (n==0) callback();
}
that you can call like this :
onLoadAll(imagesObj, function(){
// do something with imagesObj when all images are loaded
});

Ajax inserted content not accessible in DOM

I am working on a pure jquery/js site, mostly to practice some jquery. I am using a load statement to load a menu from a file of common html, like so:
$('#categoryListing').load('../common.html #categoryLinksUL');
which loads:
<ul id="categoryLinksUL">
<li>Anklets</li>
<li>Bracelets</li>
</ul>
The problem is where I am using it now I need to alter the href of the above links, but they are not part of the dom. In previous instances I was able to use .live(click... But not here. Is there a way I can accomplish this?
Specifically I need to load the links and change the href from #anklets to ?category=anklets
What about the following?
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('li a[href^="#"']').each(function () {
this.href = '?category=' + this.href.substr(1);
});
});
In my example, after the load is completed, the anonymous function is called. It takes every anchor with a hash HREF and replaces it with an HREF based on your description.
Thank you Dimitry, you solution basically worked. I finally used:
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('#categoryListing li a').each(function () {
var hashPos=this.href.indexOf("#");
var tCategory = this.href.substr(hashPos+1,this.href.length );
});
});
So why did jQuery recognize categoryListing there? I tried moving the each function outside of the load function and categoryListing did not contain any links. Is it because maybe the load was not completed when it tried to get categoryListing links? Seems like that is possible.
Thanks,
Todd

jQuery to prepend URL in img src attribute

I just need a jQuery snippet to do the prepend in img src , i.e
<img src='/img/picture1.jpg' />
The code snippet jQuery is to prepend this url
http://cdn.something.com/
so after the snippet jQuery, it becomes like
<img src='http://cdn.something.com/img/picture1.jpg' />
Any help is greatly appreciated.
so far I wrote something like
$().ready(function(){
var cdn ='http://cdn.something.com';
$('img').attrib('src', cdn);
});
However it is replaced the src rather than pre
it's not really jQuery related, anyway you could do it with .attr()what is that?:
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + src;
});
This would affect all of your <img> nodes in your markup and replace the src.
Anyway, I'm not so sure that this is a great idea. At the time theDOMready event fires, a browser might already have tried to access the old source attribute. If you must do this in Javascript, it's probably a better idea to store the path info within a custom data attribute so a browser is not tempted to load the image. This could look like:
HTML
<img src='' data-path='/img/picture1.jpg' />
JS
$(function() {
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + this.getAttribute('data-path');
});
});
This should do it. You could replace this.getAttribute() by $(this).data('path') since jQuery parses those data attributes into it's "node" data hash. But this would create another jQuery object, which really is unecessary at this point.
This should work:
$.ready(function() {
$('img').each(function() {
$(this).attr('src', cdn + $(this).attr('src'));
});
});
However I'm not sure it is the good solution for using a CDN, as the browser will have already tried to load the images from your server at the time the script will be called.
You should do this on the server side instead.
Depending what your specific problem is, you might be able to sort out this problem with a base tag, but I assume you will only want this on images, but changing the src once the page has loaded will make the images reload? IF the images don't exist in the current location you will need to change the src attribute before the page is loaded (server side).

Categories