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);
});
});
Related
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);
}
});
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>
I'm trying to get width & height of the img element. It gives 0px whatever I do.
function foo(element){
if(element){
var el=document.querySelector(element);
var img=el.getElementsByTagName("img")[0];
alert(img.style.width);
}
}
foo();
And the html:
<div id="theid" class="theclass">
<img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>
<script>
foo("#theid");
</script>
I've also tried .offsetWidth, .clientWidth and defaultView.getComputedStyle(img,"");
How about this
function foo(imgId){
var img=document.getElementById(imgId);
alert(img.offsetWidth);
}
foo('img');
Use .naturalWidth & .naturalHeight to get the actual size of image
function foo(element){
if(element){
var el=document.querySelector(element);
var img=el.getElementsByTagName("img")[0];
alert(img.naturalWidth );
}
}
foo("#theid");
DEMO
Image height/width is always returned 0px unless defined in CSS.
Try this piece of code, but you are loading the image again in this case (could be cached, but still).
var image = new Image();
// replace with appropriate library method
image.addEventListener("load", function() {
//get image height/width here
}, false);
image.src = el.getElementsByTagName("img")[0].src;
You need to use the element offsetWidth
Here is a working fiddle and the code:
function foo(element) {
if (element) {
var el = document.getElementById(element);
alert(el.offsetWidth);
}
}
foo("theid");
Note that I have used the document.getElementById only as that will get the element. No need to have getElementsByTagName in this case. And do not prefix the id with a '#' as that notation is of jquery not javascript.
<div id="theid" class="theclass">
<img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>
<script>
foo("#theimg");
</script>
You are calling foo() by passing #theimg which is not present in document, call by passing #img , i.e. like this
<script>
foo("#img");
</script>
if you use above img id, remove var img=el.getElementsByTagName("img")[0]; in your function, we can directly access it.Okay
<script>
foo("#theid");
</script>
use this to keep your function as it is. Okay
It'll give 0px, if the image failed to load otherwise it'll give the width and height of the actual image, And if you want to access the attributes like left, right, top, bottom for these attributes we need to set image position to absolute then we can access.
I have a page with multiple images with the same id, I want to use javascript to size each of these depending on their original size. It only seems to check the first instance of the image and not the others, is there any way to get this working on all images?
<img id="myImg" src="compman.gif" width="100" height="98">
<img id="myImg" src="compman.gif" width="49" height="98">
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
<script>
var x = document.getElementById("myImg").width;
var yourImg = document.getElementById('myImg');
if(x < 50) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
</script>
The reason this isnt working is that getElementById is intended to find and return a single element with that Unique element Id. If you have two elements with the same Id, only the first is returned.
So to start off with you would need to make sure that your images share a common class, instead of the same Id, like so:
<img class="myImg" src="compman.gif" width="100" height="98">
<img class="myImg" src="compman.gif" width="49" height="98">
Then instead of using document.getElementById you should use document.querySelectorAll() which will return all elements which match the selector (as a NodeList). document.querySelectorAll on MDN
Then you can turn the NodeList returned by querySelectorAll into a normal array of images using Array#slice Array#slice on MDN.
Once done then you can itterate over each of the images (Array#forEach) and set their width/height if appropriate
So here is a possible solution for what you need to do, with comments:
var images = document.querySelectorAll('.myImg'), // Fetch all images wih the 'myImg' class
imageArray = Array.prototype.slice.call(images); // Use Array.prototype.slice.call to convert the NodeList to an array
imageArray.forEach(function (img) { // Now itterate over each image in the array
if (img.width < 50) { // If the width is less than 50
img.style.setAttribute('height', '100px'); // Set the height and width
img.style.setAttribute('width', '200px');
}
});
You will also need to make sure that the code will be executed, if you are using jQuery, put the code above in an document ready function, or if you are going to use the button which you currently have. Then put the javascript above into the myFunction function your buttons onclick event would call.
Change your id to class since id is unique for each element.
Then to change everything in the class do something like
function change(x) {
elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
elements[i].style.width ="100px";
}
}
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]);
}