Demo is here.
When I click on any image, I want to get the path of that image. The problem here is that only the path of image 1 is being given every time.
Also, with that new src, i want to add that src in the image having id= cropimage
$(".img").click(function() {
var newsrc = $(".img").attr("src");
alert(newsrc);
});
Use $(this) inside click event handler to get the element that is clicked. $(this) inside event handlers is the element on which the event has occurred.
If you use $('.img'), it'll select all the elements having class img and when use attr on it, it'll return the attribute value of the first matched selector.
Demo
$(".img").click(function() {
var newsrc = $(this).attr("src");
$('#cropimage').attr('src', newsrc);
// Even Shorter Form
// $('#cropimage').attr('src', $(this).attr('src'));
});
#cropimage {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<img class="img" src="http://www.w3schools.com/images/w3schools.png" />
<br/>
<img class="img" src="https://www.google.co.in/images/icons/hpcg/ribbon-black_68.png" />
<div id="img-container">
<img src="" id="cropimage" />
</div>
Please check this link Js Fiddle it will help you.
$( ".img" ).click(function() {
var newsrc=$(this).attr("src");
//alert(newsrc);
$( "#cropimage" ).attr("src",newsrc);
});
Related
i want to get data-link attribute form an image click .
Following is my image tag
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
to get it on click this is what i am doing ,
<script type="text/javascript" language="javascript">
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).attr("data-link"));
var link = $(this).data("data-link");// tried both
console.log(link);
});
</script>
when i try to log or alert it, i get undefined
Please help me how can i fix it
Below is code snippet to help you. data-link attribute is in img tag and not in 'a' tag.
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr("data-link"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
The reason you're not getting a value is that you're getting the data-link attribute of the anchor tag as that is what represents this. If you find the child image you'll get the data-link. Here is a fiddle of it working.
<script type="text/javascript" language="javascript">
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr('data-link'));
var link = $(this).find('img').attr('data-link')
console.log(link);
});
</script>
You can try this,
<script type="text/javascript" language="javascript">
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr('data-link'));
var link = $(this).find('img').attr('data-link')
console.log(link);
});
</script>
In the context, $(this) refers to the link, not the image.
To get the image instead, use:
var link = $('img', $(this)).data('link');
That gets the img element inside the link (which is $(this)).
Read more about the .data()-method here: https://api.jquery.com/data/
In my opinion, it makes it a bit cleaner than using the .attr()-method.
You assign you data-link attribute in img tag,
so you have to write click event on img tag
$(".aclick img").click(function (e) {
e.preventDefault();
alert($(this).data("link"));
var link = $(this).data("link");
console.log(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
You click event must be on the image tag as well.
<script type="text/javascript" language="javascript">
$(".aclick img").click(function (e) {
e.preventDefault();
alert($(this).attr("data-link"));
var link = $(this).attr("data-link");// tried both
console.log(link);
});
</script>
working Fiddle
$(".aclick img").click(function (e) {
e.preventDefault();
alert($(this).attr("data-link"));
var link = $(this).attr("data-link");// tried both
console.log(link);
});
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
Img is the child element of a.so try with $(this).children('img') .And use use with data('link') instead of data('data-link')
$(".aclick").click(function(e) {
e.preventDefault();
alert($(this).children('img').attr("data-link"));
var link = $(this).children('img').data("link"); // tried both
console.log(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
this refers to the anchor tag not the image tag.
use this
$('.aclick img').attr("data-link");
On (.aclick).click() data-link will return undefined, the data-link is on the image, get the image using .find()
The find() method returns descendant elements of the selected element.
To get the value of data* use .data()
The data-* attributes is used to store custom data private to the page or application.
.data() Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
$(".aclick").click(function (e) {
e.preventDefault();
var link = $(this).find('img').data('link');
console.log(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="aclick">
<img data-link="petroliumjelly.php" src="productsimgs/petroliumjelly.png" class="img-responsive" id="2">
</a>
I'm currently have this input for my img tag:
<div id="myDiv">
<img src="/assets/images/upload/test1.jpg" />
<img src="/assets/images/upload/test2.jpg" />
<img src="/assets/images/upload/test3.jpg" />
</div>
How I can use jquery to add image path like /newfolder/ to all image tags in myDiv using jquery?
I found that jquery can alter the image src...for example
$('#myDiv img').attr('src','/newfolder/assets/images/upload/test.jpg')
Now..how I can continuously find other images in myDiv and add pre-path like /newfolder/ to all image src in myDiv?
var picRoot="/newfolder";
$('#myDiv img').each(function(){
if ( $(this).attr('src').indexOf(picRoot)!== 0){
$(this).attr('src', picRoot + $(this).attr('src'));
}
});
Call it, if your content changes.
I've been attempting to create an effect where a user clicks on an image, that image is replaced by another image which also acts as a link.
However my problem is that whenever I click the replaced image, the link doesn't work.
Fiddle: http://jsfiddle.net/ha6qp7w4/321/
$('.btnClick').on('click',function(){
$(this).attr('src','https://placekitten.com/g/200/300')
$(this).attr('href','google.com')
});
img tags don't have href properties. You need to wrap the image in an anchor and assign the url to that, or do a custom redirect.
Notice your image html on inspection of element:
<img src="https://placekitten.com/g/200/300" id="1" class="btnClick" href="google.com"> <!-- not valid! -->
This isn't valid because imgs aren't anchors!
function first() {
this.src = 'https://placekitten.com/g/200/300';
$(this).unbind("click");
$(this).on("click", second);
}
function second() {
window.location.href = "https://www.google.com";
$(this).unbind("click");
$(this).on("click", first);
}
$('.btnClick').on('click', first);
(I tried to make a fiddle but it wouldn't save, but this should work)
You need to store your actions in functions so you can revert if need be. First action is the change the source, then change the event to redirect you like a link.
here is an example.
example
html part
<img src="http://i.imgur.com/o46X87d.png" data-new="http://i.imgur.com/9lf2Mjk.png" id="1" class="btnClick" />
add data-new attribute on image with new url of image
and replace it with js
$('.btnClick').on('click',function(){
var url = $(this).attr("data-new");
$(this).attr("src", url);
});
I would use a totally different approach, but here's how to do that with the code you already have:
<div class="btnClick">
<img src="http://i.imgur.com/o46X87d.png" id="1" />
<a href="javascript:check()" id="2" style="display:none;">
<img src="http://i.imgur.com/9lf2Mjk.png" id="static" />
</a>
</div>
<script type="text/javascript">
$('.btnClick').on('click',function(){
if($('#1').is(':visible')) {
$('#1').hide();
$('#2').show();
} else {
$('#1').show();
$('#2').hide();
}
});
</script>
I purposely didn't use toggle() to better show the technique, in case you'd want to turn the click event off when the clicking image appears etc.
<img href="a" class="myImg"></img>
<img href="b" class="myImg"></img>
<img href="c" class="myImg"></img>
How can I determine the href value of the image being clicked maybe by tracking click events on elements using css class myImg. You can also modify the html if it simplifies the jquery.Thanks
$('img.myImg').click(function(){
alert(this.href); //might not work
alert(this.getAttribute('href')); //definitely should work
});
$('.myImg').click(function() {
alert($(this).attr('href'));
});
Try this
$('.myImg').click(function(){
alert($(this).attr('href'));
});
$(document).ready(function() {
$(".myImg").click(function(e) {
alert($(this).attr("href"));
});
});
"img" tag doesn't have a "href" attribute. You have to put those images between link tags ("a");
<img src=".." class="myImg">
<img src=".." class="myImg">
<img src=".." class="myImg">
Then if you want to get the href, listen for the click event on the link;
$('a').click(function(e) {
console.log('selected href:', $(this).attr('href'));
// if you want you can stop executing the href
// e.preventDefault();
});
Check http://jsfiddle.net/demods/U7D2g/
I have a layout similar to this:
<div id="..."><img src="..."></div>
and would like to use a jQuery selector to select the child img inside the div on click.
To get the div, I've got this selector:
$(this)
How can I get the child img using a selector?
The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.
jQuery("img", this);
Which is the same as using .find() like this:
jQuery(this).find("img");
If the imgs you desire are only direct descendants of the clicked element, you can also use .children():
jQuery(this).children("img");
You could also use
$(this).find('img');
which would return all imgs that are descendants of the div
If you need to get the first img that's down exactly one level, you can do
$(this).children("img:first")
If your DIV tag is immediately followed by the IMG tag, you can also use:
$(this).next();
The direct children is
$('> .child-class', this)
You can find all img element of parent div like below
$(this).find('img') or $(this).children('img')
If you want a specific img element you can write like this
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Your div contains only one img element. So for this below is right
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
But if your div contain more img element like below
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
then you can't use upper code to find alt value of second img element. So you can try this:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
This example shows a general idea that how you can find actual objects within the parent object.
You can use classes to differentiate your child's object. That is easy and fun. i.e.
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
You can do this as below :
$(this).find(".first").attr("alt")
and more specific as:
$(this).find("img.first").attr("alt")
You can use find or children as above code. For more visit Children http://api.jquery.com/children/ and Find http://api.jquery.com/find/.
See example http://jsfiddle.net/lalitjs/Nx8a6/
Ways to refer to a child in jQuery. I summarized it in the following jQuery:
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
Without knowing the ID of the DIV I think you could select the IMG like this:
$("#"+$(this).attr("id")+" img:first")
Try this code:
$(this).children()[0]
You can use either of the following methods:
1 find():
$(this).find('img');
2 children():
$(this).children('img');
jQuery's each is one option:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
You can use Child Selecor to reference the child elements available within the parent.
$(' > img', this).attr("src");
And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.
$('#divid > img').attr("src");
Also this should work:
$("#id img")
Here's a functional code, you can run it (it's a simple demonstration).
When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
Hope it helps!
You may have 0 to many <img> tags inside of your <div>.
To find an element, use a .find().
To keep your code safe, use a .each().
Using .find() and .each() together prevents null reference errors in the case of 0 <img> elements while also allowing for handling of multiple <img> elements.
// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
// Find the image using.find() and .each()
$(this).find("img").each(function() {
var img = this; // "this" is, now, scoped to the image element
// Do something with the image
$(this).animate({
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
}, 500);
});
});
#mydiv {
text-align: center;
vertical-align: middle;
background-color: #000000;
cursor: pointer;
padding: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">
<img src="" width="100" height="100"/>
</div>
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
If your img is exactly first element inside div then try
$(this.firstChild);
$( "#box" ).click( function() {
let img = $(this.firstChild);
console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
With native javascript you can use
if you've more than one image tag then use
this.querySelectorAll("img")
if only one image tag then us
this.querySelector("img")
You could use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>