JQuery click attr('src') return Undefined - javascript

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.

Related

How to alter img src onclick using jQuery or JS

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)

How to get the attribute of the first child of a div?

I have a div
<div id="img-1" class="cards"><img src="blah" alt="blah2"</div>
How do I define a variable that has the value of the alt attribute, without giving img a class or ID?
Thanks!
Try this
const img = document.getElementById('img-1').getElementsByTagName('img')[0];
console.log(img.alt);
document.getElementById('img-1').getFirstElementChild.getAttribute('alt');
You can use getFirstElementChild. As you can see it does not matter what your child element is as long as it exists. But if you are looking for alt you can simply query an img inside the div. alt is an image property.
One way is to use jQuery to select the div by class then find the first img element and get its alt attribute, then store that to a variable:
$(document).ready(function() {
var divCards = $('.cards');
// store the alt attribute of first image to variable
var attrValue = divCards.find('img').eq(0).attr('alt');
console.log(attrValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img-1" class="cards">
<img src='blah' alt='blah1'>
<img src='blah' alt='blah2'>
</div>
var altValue = document.querySelector('.card > img').alt
for(var each of document.querySelectorAll('.card > img')){
var altValue = each.alt;
....
}
JQuery equivalents
$(`.card > img`).attr('alt')
$(`.card > img`).each(function(index){ // each is bound to this
var altValue = $(this).attr('alt');
});
> forces that the img tag lies directly below the .card element
firstChild.alt should do the trick:
const alt = document.querySelector('.cards').firstChild.alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>
Alternatively you can use the first-child CSS selector:
const alt = document.querySelector('.cards > *:first-child').alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>

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
}

creating a link to images

I am trying to create a jquery code which can wrap an img tag with a link:
My code is like this:
http://prntscr.com/iuw6hc
I will paste my HTML here but basically it is a loop of many items showing within each col.
<div class="car-item gray-bg text-center first" style="height: 357px;">
<div class="car-image">
<img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">
<div class="car-overlay-banner">
<ul>
<li><i class="fa fa-link"></i></li>
I am trying like this:
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
wrapped = true;
var gURL = $('.car-overlay-banner').find('a').attr('href');
$(".img-responsive").wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
wrapped = false;
$(".img-responsive").parent().replaceWith(original);
}
});
Trying to use a href of car overlay to apply to the image too.
jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
<div id="parent">
<div id="child"></div>
</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() {
$("#imgLogo").wrap('');
});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with tag. You can also assign target="_blank" in the above tag to open the link in new window.
I think you need code like this?
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
var wrapped = true;
// find link href in .car-image(img-responsive's parent)
var gURL = $(this).parent().find('a').attr('href');
// use $(this) instead of $(".classname") to apply link only clicked image
$(this).wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
var wrapped = false;
$(this).parent().replaceWith(original);
}
});

find the img id and src and adding to the array

Heres my html code:
<div id="cmdt_1_29d" class="dt_state2" onclick="sel_test(this.id)">
<img id="cmdt_1_29i" onclick="dropit('cmdt_1_29');"
src="http://hitechpackaging.zes.zeald.com/interchange-5/en_US/ico_minus.png">
<span class="dt_link">
CARTON & BOARD
</span>
</div>
<div id="cmdt_2_31d" class="dt_istate1" onclick="sel_test(this.id)">
<img src="/site/hitechpackaging/images/items/test.jpb ">
CORRUGATED & CORNER BOARD
</div>
The dropit function modifies my img src which I dont want to, unfortunately I cant modify,
Can I somehow read the data into array before it is being modified and that I can add the data back to the image.
To remove the click handler:
var i = document.getElementById('cmd1_1_29i');
i.onclick = null;
Or, if you want to still call the original click handler:
var i = document.getElementById('cmd1_1_29i');
_onclick = i.onclick;
i.onclick = function(e) {
// do what you want here
_onclick && _onclick.apply(this, [e]);
}
โ€‹

Categories