How to alter img src onclick using jQuery or JS - javascript

I have multiple images with src URLs that all have
....content/..._gal6.jpg?format=100w
How can I use jQuery or JS to change all URLs to end with
?format=2500w
on click?

Like this
document.querySelectorAll("img").forEach(img => {
const url = new URL(img.src);
if (url.searchParams.get("format")) {
url.searchParams.set("format", "2500w")
console.log(url.toString())
img.src = url.toString()
}
})
<img src="bla.jpg?format=250w">
<img src="bla.jpg">
<img src="bla.jpg?format=350w">

Using Javascript:
Change the src property of the image:
function changeImage(){
document.getElementById('test-image').src = "https://url-to-second-image.com/image.png";
}
You can call the function using the click event in the html:
<img id="test-image" src="the-url/first_image.jpg" onclick="changeImage()">
Here is a jsfiddle: https://jsfiddle.net/f5mwext3/2/
The same way you can change only part of the name (I'm using whole external files for convenience)

Related

How get src value when click on one of the mulitple images in javascript?

I have 3 images in my web page. I want to get src value every time when I clicked on any image. I tried following code but its not working with multiple images.
<div class="test">
</div>
</div>
</div>
</div>
<script type="text/javascript">
function filename(){
//var fullPath = document.getElementsByClassName('dImage').src;
var fullpath = document.getElementsByClassName('dImg').src
console.log(fullPath);
var filename = fullPath.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
//window.location.href = "web-rocketcreator.html?="+fileid;
console.log(fileid);
}
</script>
As the other answers have mentioned the specific problem area, here's an alternative solution.
Instead of attaching a click event to each image you can attach one to the container and listen for events as they bubble up the DOM (known as event delegation.)
// Grab the container, and add an event listener to it
const imageContainer = document.querySelector('.test');
imageContainer.addEventListener('click', filename, false);
function filename(event) {
// Pick out the src attribute from target element
// (the image that was clicked on)
const { target: { src } } = event;
// Use the src as the basis for the rest of
// your calculations
var filename = src.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
console.log(`web-rocketcreator.html?=${fileid}`);
}
.test a {
display: block;
}
<div class="test">
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-1.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-2.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-3.png" alt="">
</a>
</div>
To get a reference to the object which triggered the click event you need to pass the keyword this as a parameter.
In your case this object is the <a> element. To get it's nested children - the <img> element you need to call the .children method which returns an array. Since there's just the image element you can directly reference it using children[0] and ultimately add the .src property to retrieve the source.
function filename(element){
console.log(element.children[0].src);
}
<div class="test">
</div>
Get src value from image when clicking on it
When you call a function from onClick() you can pass 'this' to the function. This way you will directly have a reference to the clicked element inside the functon
<img src="xxxx.jpg" onclick="myFunction(this)" />
function myFunction(element) {
const src = element.src;
}
Get src value from image when clicking on parent container
<a onclick="myFunction(this)"><img src="xxxx.jpg" /></a>
function myFunction(link) {
const src = link.children[0].src
}

How to change an img src with javascript?

I know there are other questions like this and I've tried following them I'm just not aware of what exactly I'm doing wrong. I've declared the pic variable as being linked to the image with the corresponding id of 'pic' and I've tried many different examples and trying to follow other questions like this but to no avail.
--- THE REAL QUESTION ----
I would like the image to change its src to another one that I have in my workspace with the click of a button.
HTML:
<img class="trans" id="pic" src="images/link_rouge.png" alt="" width="1000" height="333" />
JavaScript:
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
I know the functions already work with the buttons because they are affecting some divs on the page that change color the only things not changing are the images.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Use addEventListener over button elements to attach click events and bind your handler functions to those events.
var pic = document.getElementById('pic');
function rouge() {
pic.src = "http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png";
}
function blue() {
pic.src = "http://bin.smwcentral.net/u/1944/Link%2BBlue%2BTP%2Bshrunk.png";
}
document.getElementById('btn1').addEventListener('click', rouge);
document.getElementById('btn2').addEventListener('click', blue);
img {
width: 200px;
}
<button id='btn1'>rouge</button>
<button id='btn2'>blue</button>
<br/>
<img class="trans" id="pic" src="http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png" alt="" width="1000" height="333" />
There's a chance your page has not loaded before pic is set equal to document.getElementById('pic');.
You can use something like jQuery's $(document).ready() function (or document.addEventListener("DOMContentLoaded", handler);) to ensure your page is fully loaded before assigning the pic variable.
$( document ).ready(function() {
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
});
Note: You will need to pull the JQuery library into your project to use this method. See here.
Also, you can read this post to learn a little more about HTML/JavaScript and page loading.

Use data from img tag

I have an image tag that looks like:
<img data-original="imgserv/profilepics/2/702296.jpg" src="imgserv/blank.JPG"
id="702296" user_ip="65.346.36.192" class="lazy">
In jQuery, if I do
$('.lazy').on('click', function() {
alert(this.id);
});
I'll get the specific id I need.
How can I make it so that I can also retrieve the data inside user_ip?
You can select that attribute like this (inside a click handler):
var user_ip = $(this).attr('user_ip');
I suggest you make it a data attribute like data-original:
<img ... data-user-ip="...">
Then:
var user_ip = $(this).data('user-ip');

JQuery click attr('src') return Undefined

The images loads from ko.observableArray
<ul data-bind="foreach: images">
<li>
<div class="photo">
<h2></h2>
<img data-bind="attr:{src: '/images/'+path}, click: $root.addImageUrl">
</div>
</li>
After click on the image i want to get image src and add it to another ko.observableArray
I have following script
self.addImageUrl = function () {
var src = $("img",this).attr('src');
self.selectedImages.push(src);
};
But returns Undefined.
You are wrong to use this. In addImageUrl function this is not element. I can suggest you to use img object instead (itэы not explicitly passed to function):
self.addImageUrl = function (img) {
var src = '/images/' + img.path;
self.selectedImages.push(src);
};
Demo
The selector $("img",this).attr('src'); is wrong.
Use $(this).attr('src'); to get the src of the clicked image.

How to rewrite inner img tags source with new image path using JQuery

How to rewrite image path of following img tag with new image path while click on span element
<span id="cc-element-1">
<img src="http://localhost/example/orig/abc.jpg"/>
</span>
Expected result as follows,
<span id="cc-element-1">
<img src="http://localhost/example/cloned/abc.jpg"/>
</span>
$('#cc-element-1').click(function() {
var $img = $(this).children('img');
$img.attr('src', $img.attr('src').replace(/orig/, 'cloned'));
});
If doing a read-modify-write on an attribute you should use the callback function based version of .attr over the code given by #Sahil:
$('#cc-element-1').click(function() {
var $img = $(this).children('img');
$img.attr('src', function(index, val) {
return val.replace(/orig/, 'cloned'));
});
});
This avoids the need to call $img.attr(src) twice - once to read and once to write.
It's therefore more efficient, particularly so if the original selector is non-trivial.
$("#cc-element-1 > img").click(function() {$(this).attr('src', 'http://localhost/example/cloned/abc.jpg')})
try something like this:
var newSrc = 'http://localhost/example/cloned/abc.jpg';
$('span#cc-element-1').click(function(){
$(this).children('img').attr('src', newSrc);
});
See an example here:
http://jsfiddle.net/expertCode/FdgzJ/

Categories