Jquery replaceWith keep onclick - javascript

How can I keep onclick="" value with JQuery replaceWith ? I'm making a assets system that preload every image and put it on a Javascript image() object, and using a special data attribute for img urls
<img data-assets="images/test.png" onclick="alert('test')">
turn into : (using jquery replaceWith)
<img src="assets/images/test.png">
What I want:
<img src="assets/images/test.png" onclick="alert('test')">
My code:
$("[data-assets]").each(function() {
$(this).replaceWith(Game.Preloading.Assets.Images[$(this).data('assets')]);
});
How can I fix that ? Thanks

While iterating over each [data-assets] element, you could set the corresponding onclick attribute before replacing the element:
$("[data-assets]").each(function() {
var $newImg = $(Game.Preloading.Assets.Images[$(this).data('assets')]);
$newImg.attr('onclick', $(this).attr('onclick'));
$(this).replaceWith($newImg);
});
However, it would be better to just add a src attribute on the existing element rather than replacing it:
$("[data-assets]").each(function() {
this.src = $(Game.Preloading.Assets.Images[$(this).data('assets')]).attr('src');
});
Ideally, you should be using unobtrusive JavaScript and avoiding the inline JavaScript event listeners, but both of the above snippets should work.

I think you would be better off to simple query for your attribute, then use the each method to update the SRC attribute on each matched element.
Im on my phone so a more detailed answer is difficult...
But here goes
$("[data-assets]").each(function(){ $(this).attr("src", Game.Preloading.Assets.Images[$(this).data('assets')]); });

Related

How to pass an alt attribute in an on click method

Hello I have the following code:
<img alt="image321" onclick="image(//here i want to pass the alt attribute to my function Bild()//);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
<script>
function image(alt){
alert(alt.src);
}
</script>
I have my image and have given it an alt attribute with the value "image321".Now I want to pass this value to my function image() and output the value with alert as soon as I clicked on the image. But the output is always undifined. Could someone please help me how to solve this problem.
Many greetings Nils
First thing would be to avoid inline handlers - they have quite a few problems, too many to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
Inside the listener, reference this to get to the clicked element, and its src property to get to its src:
document.querySelector('img').addEventListener('click', function() {
console.log(this.src);
console.log(this.alt);
});
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
function myfunc(img){
alert(img.alt);
}
<img alt="image321" onclick="myfunc(this);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
You should try using this, which sends the element that you run the function with.
Here is an example:
function image(alt) {
alert(alt.src);
}
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" onclick="image(this)"/>

How to add new image element to html href link with javascript?

I have a problem creating a new image element to this code here:
Sound Packs
Unfortunately, I do not have access to the HTML code because it belongs to a locked template of "jimdo". I can only insert CSS codes and javascript in the "head area". Is there a way to add an image element to this HTML code with javascript?
Yes, there is a way to do this using just javascript. Firstly you need to set the window.onload callback to a function. Within this function, you can then get the element you want to add the image to. Here I added the image to the element with the attribute data-link-title which is equal to "Sound Packs".
Lastly, you can use .innerHTML on this element to add the HTML you want to add within this element. Here I added a <br /> followed by an <img> tag:
document.body.onload = function() {
let soundPacks = document.querySelector('[data-link-title="Sound Packs"]');
soundPacks.innerHTML += "<br /><img src='https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a' alt='StackOverflow Logo'/>";
}
Sound Packs

Get image src without loading the image?

I have a html snippet being returned through ajax. The snippet is an <img> tag.
<img src="image.jpg" />
I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.
I have the following code currently extracting the src attribute:
var src = $(value).attr('src');
However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.
How can I extract the value of the src attribute without causing the browser to load the image?
I solved this by changing the name of the src attribute before loading it into jquery.
value = value.replace('src', 'data-src');
var src = $(value).attr('data-src');
Doing this allows me to extract the value without causing the browser to attempt to load the images.
Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.
So you'd do something like this in your HTML:
<img data-img-src="abc.jpg" class="my-image" />
Then in your jQuery:
var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.
$.ajax('someURL.html', function(data){
var html = data.replace(/\ssrc/g, ' data-src'),
img = $(html),
src = 'some/path/' + img.data('src');
img.attr('src', src);
$('#container').append(img);
});
If you just have the string , like <img src="image.jpg" /> why dont you go for regex?
Something like: /[\"\'][a-z0-9A-Z\.]*/.
PS:My regex skills are poor,so you could manipulate it accordingly.
Use
var string = '<img src="image.png">';
var matches = string.match(/src\=("|')(.*?)\1/);
console.log(matches[2]);
You can simply remove the attribute after accessing it.
This will not load the invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'),
src= s.attr('src');
s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove removeAttr(), and it will attempt to load the image.

Change attribute from data-src to src WITHOUT jQuery

I am building a lightbox, in pure JavaScript. I currently have my images loading via AJAX, but i know it is easier to just have the img data-src attribute being replaced onclick to src.
I however have NO idea how this is done in pure JavaScript, by that i mean, without using any libraries.
Can anyone tell me how this is done?
to sum up: How do i change ex:
<img data-src="URL"/>
to:
<img src="URL"/>
without jQuery.
You can do it like shown below:
var imgEl = document.getElementsByTagName('img');
for (var i=0; i<imgEl.length; i++) {
if(imgEl[i].getAttribute('data-src')) {
imgEl[i].setAttribute('src',imgEl[i].getAttribute('data-src'));
imgEl[i].removeAttribute('data-src'); //use only if you need to remove data-src attribute after setting src
}
}
The above code will fetch all img tags, check if they have a data-src attribute and if present, replace it with src.
Demo Fiddle
Get a handle on the image element, and then set it's src property, using the value from getAttribute().
Plain Javascript doesn't have any helper functions to handle data-* attributes, it just treats them as any other attribute.
var img = document.getElementById("myimg");
img.src = img.getAttribute("data-src");
You can use forEach with querySelectorAll
var imageElements = document.querySelectorAll('img');
imageElements.forEach(c=> c.setAttribute('src',c.getAttribute('data-src')));
img{width:100px;}
<img data-src='https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png' />

Replace All innerhtml text with Javascript

I've been trying for hours and I've looked a lot of samples on StackOverflow, but I can't fix my simple script.
I grabbed DOM with jQuery
var color = $('#bscontainer').html();
and now the content of color is:
<img src="resources/P/Blue_BG_2Col.png" id="bg">
<img src="resources/P/Blue_Content_2Col.png" id="content">
<img src="resources/P/Blue_Title_ExchangeRate.png" id="title">
<img src="resources/P/Blue_SubTitle_2Col.png" id="subtitle">
<img src="resources/P/Blue_Disclaimer_Disclaimer.png" id="disclaimer">
My idea is to change all the Blue to Green, and I already try this:
curColor="Blue";
newColor="Green";
t=color.replace(curColor,newColor);
It simply doesn't works. Any ideas?
To answer your question directly, replace in javascript when it takes a string parameter as the needle, only replaces the first instance. To replace all instances within a string, use a global regular expression:
str.replace(/Blue/g, 'Green');
You really ought to just modify the src attributes of the img tags though. That is the more proper way to attack this. Changing the html like you are trying to will lose any events or data bound to the DOM elements.
So basically you want to find each image in your color element and replace Blue with Green in the src attribute -- This is one way you can do it:
var color = $('#bscontainer');
color.find('img').each(function(){
curColor="Blue";
newColor="Green";
this.src = this.src.replace(curColor,newColor);
});
No need for the .html() part of your code...
Use a callback function to actually update the HTML, and use a regular expression (object) to replace all instances at once:
$('#bscontainer').html(function (i, str) {
curColor = new RegExp("Blue","g"); // global replace
newColor = "Green";
return str.replace(curColor, newColor);
});

Categories