find the img id and src and adding to the array - javascript

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]);
}
​

Related

Using vanilla JS to set image src from data-attribute

I'm looking for a way to set the src of an image - in a modal - using the data attribute of a clickable element.
The markup for the element looks like this (there could be multiple of these on a page):
<span class="tooltip" data-imageToSet="someimage.jpg">Click me</span>
<div id="modal">
<img id="image" src="placeholder.jpg" />
</div>
<script>
var modal = document.getElementById('modal'),
modalImage = document.getElementById('image');
document.addEventListener('click', function(event) {
if (event.target.classList.contains('tooltip')) {
modal.classList.toggle('shown');
modalImage.src = event.currentTarget.dataset.imageToSet;
}
});
</script>
From what I've been reading up, this should work? But I keep getting a console error:
Uncaught TypeError: Cannot read property 'imageToSet' of undefined at HTMLDocument.<anonymous> ((index):1)
You have two issues. currentTarget will be the element you bound the click to so it will be document. The second issue is camel case does work with dataset, you need to use dash.
var modal = document.getElementById('modal'),
modalImage = document.getElementById('image');
document.addEventListener('click', function(event) {
if (event.target.classList.contains('tooltip')) {
modal.classList.toggle('shown');
console.log(event.target)
modalImage.src = event.target.dataset.imageToSet;
}
})
<span class="tooltip" data-image-to-set="http://placekitten.com/300/300">Click me</span>
<div id="modal">
<img id="image" src="http://placekitten.com/g/200/300" />
</div>
First you check if the target (i.e. the element that is clicked) has the tooltip class
event.target.classList.contains('tooltip')
But then you use the currentTarget (i.e. the element to which the event handler is bound: document) to read the dataset.
modalImage.src = event.currentTarget.dataset.imageToSet
You need to continue to use the target throughout.

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

javascript - how to get img tags from any element?

I want to get img tags attribute values from any element, img tags could be more than 1, and also can be randomized.
like,
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
I want to grab their title attribute values and then want to store in some var currentHTML; with all existing div data.
and then insert into any element just like $('#div').html(currentHTML);
and output should be like this,
hellow :) how are u :D
How can I do this?
Thanks in advance.
Try this:
$("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
Fiddle. Its just looping through each image and replacing it (with replaceWith()) with its own title attribute.
UPDATE:
Things got more complex. Check this snippet:
// The text result you want
var currentHTML = "";
// Instead of search for each image, we can search of elements that
// contains images and you want to get their text
$(".images").each(function()
{
// Check note #1
var cloned = $(this).clone().css("display", "none").appendTo($("body"));
// Here we select all images from the cloned element to what
// we did before: replace them with their own titles
cloned.find("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
// Add the result to the global result text
currentHTML+= cloned.html();
});
// After all, just set the result to the desired element's html
$("#div").html(currentHTML);
Note #1: Here is what is happening in that line:
var cloned = here we create a var which will receive a cloned element;
the cloned element will the current element $(this).clone();
this element must be hidden .css("display", "none");
and then appended to the document's body .appendTo($("body"));.
Note that in your initial html, the div containing the images received the class images:
<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>
So you can do that on more than one element. I hope this helps.
Here's a neat little function you can reuse.
$(function(){
function getImageReplace($el) {
var $copy = $el.clone();
$copy.find('img').each(function(){
$(this).replaceWith($(this).attr('title'));
});
return $copy.text();
}
//now you can use this on any div element you like
$('#go').click(function() {
alert(getImageReplace($('div')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
<button id='go'>Convert images</button>

javascript color thief in jquery nested loop

I have some dynamically generated content on which I need to use color thief to find the dominant colour. Here's the final dynamic output:
<div class="image_product">
<img style="display:none;" src="image1.jpg">
<img style="display:none;" src="image2.jpg">
</div>
<div class="image_product">
<img style="display:none;" src="image3.jpg">
<img style="display:none;" src="image4.jpg">
</div>
And here's the script I'm trying:
var colorThief = new ColorThief();
$('div.image_product').each(function() {
$(this).find('img').each(function() {
var color = colorThief.getColor(this[0]);
console.log(color);
});
});
I've managed to get it working in other areas where I know there is only one image, with the following code:
var colorThief = new ColorThief();
$('div.basket_item_image').each(function() {
if($(this).children("img").length > 0)
{
var img = $(this).find('img');
var color = colorThief.getColor(img[0]);
console.log(color);
}
});
And I know you have to add the [0] when using it with JQuery to make it access the DOM correctly, but I can't see how my middle code isn't working. Any ideas?
You don't need the this[0]. Inside each(), this is the current HTML element being iterated and not a jQuery object, per the docs:
More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.
Therefore, just use this to access the current element (the current <img />) whilst inside each().
var colorThief = new ColorThief();
$('div.image_product').each(function() {
$(this).find('img').each(function() {
var color = colorThief.getColor(this);
console.log(color);
});
});

Categories