Javascript как изменить src путь изображения

How can I change the src attribute of an img tag using javascript? Edit at first I have a default src ...

How can I change the src attribute of an img tag using javascript?

<img src="../template/edit.png" name="edit-save" alt="Edit" />

at first I have a default src which is «../template/edit.png» and I wanted to change it with «../template/save.png» onclick.

UPDATED:
here’s my html onclick:

<a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a>

and my JS

function edit()
{   
    var inputs = document.myform;
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }
}

I’ve tried inserting this inside the edit(), it works but need to click the image twice

var edit_save = document.getElementById("edit-save");
    edit_save.onclick = function(){
       this.src = "../template/save.png";
    }

Andy's user avatar

Andy

4,0802 gold badges24 silver badges47 bronze badges

asked Jul 30, 2012 at 13:17

Sam San's user avatar

0

Give your img tag an id, then you can

document.getElementById("imageid").src="../template/save.png";

answered Jul 30, 2012 at 13:18

Matthias's user avatar

MatthiasMatthias

12.3k13 gold badges34 silver badges55 bronze badges

2

You can use both jquery and javascript method:
if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.

Adam Joseph Looze's user avatar

answered Feb 12, 2015 at 17:58

chandanjha's user avatar

chandanjhachandanjha

8836 silver badges5 bronze badges

2

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

Foreever's user avatar

Foreever

6,8018 gold badges48 silver badges55 bronze badges

answered Dec 3, 2013 at 13:52

Alessandro Pirovano's user avatar

2

its ok now

function edit()
{   
    var inputs = document.myform;
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }

    var edit_save = document.getElementById("edit-save");

       edit_save.src = "../template/save.png";                              
}

answered Jul 30, 2012 at 14:33

Sam San's user avatar

Sam SanSam San

6,4178 gold badges32 silver badges51 bronze badges

0

Give your image an id. Then you can do this in your javascript.

document.getElementById("blaah").src="blaah";

You can use this syntax to change the value of any attribute of any element.

answered Jul 18, 2014 at 23:31

Ben's user avatar

BenBen

2,15521 silver badges30 bronze badges

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

answered Jul 30, 2012 at 13:20

Donatas Olsevičius's user avatar

1

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you’re in control of the code, it’s better to assign an id to the image a get a reference with getElementById (since it’s the fastest method to retrieve an element)

answered Jul 30, 2012 at 13:21

Fabrizio Calderan's user avatar

Fabrizio CalderanFabrizio Calderan

119k26 gold badges168 silver badges177 bronze badges

In this case, as you want to change the src of the first value of your element, you have no need to build up a function. You can change this right in the element:

<a href='#' onclick='this.firstChild.src="../template/save.png"')'>
  <img src="../template/edit.png" id="edit-save"/>
</a>

You have several ways to do this. You can also create a function to automatize the process:

function changeSrc(p, t) { /* where p: Parent, t: ToSource */
  p.firstChild.src = t
}

Then you can:

<a href='#' onclick='changeSrc(this, "../template/save.png");'>
  <img src="../template/edit.png" id="edit-save"/>
</a>

answered Oct 3, 2014 at 17:24

Marcelo Camargo's user avatar

Marcelo CamargoMarcelo Camargo

2,1902 gold badges21 silver badges50 bronze badges

My DOM looks like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

Is this possible or do I have to use CSS to change the images?

CupawnTae's user avatar

CupawnTae

14k3 gold badges28 silver badges60 bronze badges

asked Feb 16, 2009 at 19:23

user67033's user avatar

5

You can use jQuery’s attr() function. For example, if your img tag has an id attribute of ‘my_image’, you would do this:

<img id="my_image" src="first.jpg" alt="Insert link 1 alt text here" />

Then you can change the src of your image with jQuery like this:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

Andy's user avatar

Andy

4,0802 gold badges24 silver badges47 bronze badges

answered Feb 16, 2009 at 19:27

jonstjohn's user avatar

jonstjohnjonstjohn

59.1k8 gold badges42 silver badges55 bronze badges

0

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc.
You will need to use jQuery .load() method to do stuff after image load.

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://stackoverflow.com/a/670433/561545

Community's user avatar

answered Mar 22, 2012 at 16:35

Mohsen's user avatar

MohsenMohsen

63.6k33 gold badges158 silver badges184 bronze badges

2

In case you update the image multiple times and it gets CACHED and
does not update, add a random string at the end:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

answered Jan 16, 2020 at 20:05

kintsukuroi's user avatar

kintsukuroikintsukuroi

1,22015 silver badges13 bronze badges

1

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

This solution is useful and it works but if changing the path change also the path for image and not working.

I’ve searching for resolve this issue but not found nothing.

The solution is putting the » at the beginning the path:
$("#myid").attr('src', 'images/sample.gif');

This trick is very useful for me and I hope it is useful for other.

Hassaan's user avatar

Hassaan

7,0235 gold badges29 silver badges50 bronze badges

answered Jul 20, 2016 at 10:01

wphonestudio's user avatar

IF there is not only jQuery or other resource killing frameworks — many kb to download each time by each user just for a simple trick — but also native JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

asawyer's user avatar

asawyer

17.4k8 gold badges57 silver badges85 bronze badges

answered Sep 13, 2011 at 21:44

inco's user avatar

incoinco

1911 silver badge2 bronze badges

1

I’ll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)… whether you have 2 or more images in your HTML.

I’ll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

The full code

$(function() {

    var $images = $("#d1 > .c1 > a").clone();  

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );  

    $("#d1 > .c1 > a").click(function(event) { 

        $(this).children().attr("src", 
                        $("img", $images).eq(++$imgShow % $length).attr("src") );
        event.preventDefault();

    });
});

The breakdown

  1. Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality… for example display the working link below each image):

        var $images = $("#d1 > .c1 > a").clone();  ;
    
  2. Check how many images were in the HTML and create a variable to track which image is being shown:

    var $length = $images.length;
    var $imgShow = 0;
    
  3. Modify the document’s HTML so that only the first image is being shown. Delete all the other images.

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); 
    
  4. Bind a function to handle when the image link is clicked.

        $("#d1 > .c1 > a").click(function(event) { 
            $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") );
            event.preventDefault();
        });
    

    The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images… cycling through each image in order and restarting at the first image when the last image is reached.

    Additionally, .attr() is used to get and set the «src» attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I’m interested in.


jsFiddle example with 3 images

You can also store the srcs in an array.
jsFiddle example with 3 images

And here’s how to incorporate the hrefs from the anchor tags around the images:
jsFiddle example

answered Sep 11, 2010 at 23:27

Peter Ajtai's user avatar

Peter AjtaiPeter Ajtai

56.6k13 gold badges121 silver badges140 bronze badges

Hope this can work

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>
$(document).ready(function() {
    var flag = 0;
    $("button#changeSize").click(function() {
        if (flag == 0) {
            $("#dummyimage").attr("src", "http://dummyimage.com/250x155/");
            flag = 1;
        } else if (flag == 1) {
            $("#dummyimage").attr("src", "http://dummyimage.com/450x255/");
            flag = 0;
        }
    });
});

Mohammad's user avatar

Mohammad

20.8k15 gold badges53 silver badges82 bronze badges

answered May 21, 2018 at 12:45

Zeeshan's user avatar

ZeeshanZeeshan

2211 gold badge3 silver badges7 bronze badges

2

You should add id attribute to your image tag, like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

answered Apr 28, 2019 at 11:17

Mr Bitmap's user avatar

Mr BitmapMr Bitmap

2014 silver badges20 bronze badges

You can also do this with jQuery in this way:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

You can have a condition if there are multiple states for the image source.

answered Sep 28, 2010 at 0:44

FernandoEscher's user avatar

FernandoEscherFernandoEscher

2,9202 gold badges28 silver badges27 bronze badges

1

I had the same problem when trying to call re captcha button.
After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,…):

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

‘theUrl’ is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

answered Jul 24, 2017 at 12:57

Kayvan Tehrani's user avatar

Kayvan TehraniKayvan Tehrani

2,9702 gold badges31 silver badges45 bronze badges

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });

MasterAler's user avatar

MasterAler

1,5743 gold badges23 silver badges33 bronze badges

answered Apr 4, 2019 at 13:59

Abhijit Poojari's user avatar

I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.

Codepen

$(function() {

  //Listen for a click on the girl button
  $('#girl-btn').click(function() {

    // When the girl button has been clicked, change the source of the #square image to be the girl PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
  });

  //Listen for a click on the plane button
  $('#plane-btn').click(function() {

    // When the plane button has been clicked, change the source of the #square image to be the plane PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
  });

  //Listen for a click on the fruit button
  $('#fruits-btn').click(function() {

    // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
  <button id="girl-btn">Girl</button>
  <button id="plane-btn">Plane</button>
  <button id="fruits-btn">Fruits</button>

  <a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>

answered Dec 30, 2020 at 15:46

Neil Meyer's user avatar

Neil MeyerNeil Meyer

4313 silver badges10 bronze badges

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

answered Apr 4, 2016 at 17:48

Anyone_ph's user avatar

Anyone_phAnyone_ph

6166 silver badges15 bronze badges

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

answered Nov 13, 2018 at 10:46

Wachaga Mwaura's user avatar

Wachaga MwauraWachaga Mwaura

3,1123 gold badges26 silver badges30 bronze badges

Just an addition, to make it even more tiny:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});

answered Oct 27, 2018 at 16:53

Szél Lajos's user avatar

Szél LajosSzél Lajos

4394 silver badges11 bronze badges

Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

Community's user avatar

answered Jun 14, 2020 at 22:00

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.6k29 gold badges352 silver badges327 bronze badges

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

$(document).ready(function()
{
    $("button").click(function()
    {
      $("#d1 .c1 a").each(function()
      {
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');
      });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

<button>Change The Images</button>

answered Apr 8, 2016 at 5:55

Abrar Jahin's user avatar

Abrar JahinAbrar Jahin

13.7k23 gold badges108 silver badges159 bronze badges

My DOM looks like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

Is this possible or do I have to use CSS to change the images?

CupawnTae's user avatar

CupawnTae

14k3 gold badges28 silver badges60 bronze badges

asked Feb 16, 2009 at 19:23

user67033's user avatar

5

You can use jQuery’s attr() function. For example, if your img tag has an id attribute of ‘my_image’, you would do this:

<img id="my_image" src="first.jpg" alt="Insert link 1 alt text here" />

Then you can change the src of your image with jQuery like this:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

Andy's user avatar

Andy

4,0802 gold badges24 silver badges47 bronze badges

answered Feb 16, 2009 at 19:27

jonstjohn's user avatar

jonstjohnjonstjohn

59.1k8 gold badges42 silver badges55 bronze badges

0

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc.
You will need to use jQuery .load() method to do stuff after image load.

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://stackoverflow.com/a/670433/561545

Community's user avatar

answered Mar 22, 2012 at 16:35

Mohsen's user avatar

MohsenMohsen

63.6k33 gold badges158 silver badges184 bronze badges

2

In case you update the image multiple times and it gets CACHED and
does not update, add a random string at the end:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

answered Jan 16, 2020 at 20:05

kintsukuroi's user avatar

kintsukuroikintsukuroi

1,22015 silver badges13 bronze badges

1

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

This solution is useful and it works but if changing the path change also the path for image and not working.

I’ve searching for resolve this issue but not found nothing.

The solution is putting the » at the beginning the path:
$("#myid").attr('src', 'images/sample.gif');

This trick is very useful for me and I hope it is useful for other.

Hassaan's user avatar

Hassaan

7,0235 gold badges29 silver badges50 bronze badges

answered Jul 20, 2016 at 10:01

wphonestudio's user avatar

IF there is not only jQuery or other resource killing frameworks — many kb to download each time by each user just for a simple trick — but also native JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

asawyer's user avatar

asawyer

17.4k8 gold badges57 silver badges85 bronze badges

answered Sep 13, 2011 at 21:44

inco's user avatar

incoinco

1911 silver badge2 bronze badges

1

I’ll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)… whether you have 2 or more images in your HTML.

I’ll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

The full code

$(function() {

    var $images = $("#d1 > .c1 > a").clone();  

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );  

    $("#d1 > .c1 > a").click(function(event) { 

        $(this).children().attr("src", 
                        $("img", $images).eq(++$imgShow % $length).attr("src") );
        event.preventDefault();

    });
});

The breakdown

  1. Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality… for example display the working link below each image):

        var $images = $("#d1 > .c1 > a").clone();  ;
    
  2. Check how many images were in the HTML and create a variable to track which image is being shown:

    var $length = $images.length;
    var $imgShow = 0;
    
  3. Modify the document’s HTML so that only the first image is being shown. Delete all the other images.

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); 
    
  4. Bind a function to handle when the image link is clicked.

        $("#d1 > .c1 > a").click(function(event) { 
            $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") );
            event.preventDefault();
        });
    

    The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images… cycling through each image in order and restarting at the first image when the last image is reached.

    Additionally, .attr() is used to get and set the «src» attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I’m interested in.


jsFiddle example with 3 images

You can also store the srcs in an array.
jsFiddle example with 3 images

And here’s how to incorporate the hrefs from the anchor tags around the images:
jsFiddle example

answered Sep 11, 2010 at 23:27

Peter Ajtai's user avatar

Peter AjtaiPeter Ajtai

56.6k13 gold badges121 silver badges140 bronze badges

Hope this can work

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>
$(document).ready(function() {
    var flag = 0;
    $("button#changeSize").click(function() {
        if (flag == 0) {
            $("#dummyimage").attr("src", "http://dummyimage.com/250x155/");
            flag = 1;
        } else if (flag == 1) {
            $("#dummyimage").attr("src", "http://dummyimage.com/450x255/");
            flag = 0;
        }
    });
});

Mohammad's user avatar

Mohammad

20.8k15 gold badges53 silver badges82 bronze badges

answered May 21, 2018 at 12:45

Zeeshan's user avatar

ZeeshanZeeshan

2211 gold badge3 silver badges7 bronze badges

2

You should add id attribute to your image tag, like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

answered Apr 28, 2019 at 11:17

Mr Bitmap's user avatar

Mr BitmapMr Bitmap

2014 silver badges20 bronze badges

You can also do this with jQuery in this way:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

You can have a condition if there are multiple states for the image source.

answered Sep 28, 2010 at 0:44

FernandoEscher's user avatar

FernandoEscherFernandoEscher

2,9202 gold badges28 silver badges27 bronze badges

1

I had the same problem when trying to call re captcha button.
After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,…):

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

‘theUrl’ is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

answered Jul 24, 2017 at 12:57

Kayvan Tehrani's user avatar

Kayvan TehraniKayvan Tehrani

2,9702 gold badges31 silver badges45 bronze badges

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });

MasterAler's user avatar

MasterAler

1,5743 gold badges23 silver badges33 bronze badges

answered Apr 4, 2019 at 13:59

Abhijit Poojari's user avatar

I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.

Codepen

$(function() {

  //Listen for a click on the girl button
  $('#girl-btn').click(function() {

    // When the girl button has been clicked, change the source of the #square image to be the girl PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
  });

  //Listen for a click on the plane button
  $('#plane-btn').click(function() {

    // When the plane button has been clicked, change the source of the #square image to be the plane PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
  });

  //Listen for a click on the fruit button
  $('#fruits-btn').click(function() {

    // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
  <button id="girl-btn">Girl</button>
  <button id="plane-btn">Plane</button>
  <button id="fruits-btn">Fruits</button>

  <a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>

answered Dec 30, 2020 at 15:46

Neil Meyer's user avatar

Neil MeyerNeil Meyer

4313 silver badges10 bronze badges

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

answered Apr 4, 2016 at 17:48

Anyone_ph's user avatar

Anyone_phAnyone_ph

6166 silver badges15 bronze badges

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

answered Nov 13, 2018 at 10:46

Wachaga Mwaura's user avatar

Wachaga MwauraWachaga Mwaura

3,1123 gold badges26 silver badges30 bronze badges

Just an addition, to make it even more tiny:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});

answered Oct 27, 2018 at 16:53

Szél Lajos's user avatar

Szél LajosSzél Lajos

4394 silver badges11 bronze badges

Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

Community's user avatar

answered Jun 14, 2020 at 22:00

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

80.6k29 gold badges352 silver badges327 bronze badges

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

$(document).ready(function()
{
    $("button").click(function()
    {
      $("#d1 .c1 a").each(function()
      {
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');
      });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

<button>Change The Images</button>

answered Apr 8, 2016 at 5:55

Abrar Jahin's user avatar

Abrar JahinAbrar Jahin

13.7k23 gold badges108 silver badges159 bronze badges

This is a tutorial on how to change the “src” attribute of an image using JavaScript.

The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.

In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.

Changing the src attribute using regular JavaScript.

If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.

Take a look at the example below:

<img id="myImage" src="https://thisinterestsme.com/LOGO.png">

<script>
    //Modify the src attribute of the image with the ID "myImage"
    document.getElementById("myImage").src = 'img/new-image.jpg';
</script>

If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.

A more verbose example for those of you who want to understand what is going on here:

//Get our img element by using document.getElementById
var img = document.getElementById("myImage");

//Set the src property of our element to the new image URL
img.src = 'img/new-image.jpg';

In this case, we have broken the process up into two steps:

  1. We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
  2. After retrieving the img, we were able to modify its src attribute and assign a new URL.

This will force the browser to load our new image.

Changing the img src using jQuery.

If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:

//Change the img property using jQuery's attr method
$("#myImage").attr("src", 'img/new-image.jpg');

In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.

Determining when the new image is loaded.

If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:

//Change the img property and use load() to figure out when
//the new image has been loaded
$("#myImage").attr("src", 'img/new-image.jpg').load(function(){
    alert('New image loaded!');
});

Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.

Слайдер javascript смена картинки пример!? Будем делать слайдер с нуля пошагово, от простого к сложному! И конечно же слайдер будет с использование javascript. На самом деле слайдер это вопрос : Как сменить, заменить картинку в js, как поменять путь до картинки в javascript, примеры замены картинок в реальном времени, примеры, все наша тема!

  • Для того, чтобы заменить картинку с помощью javascript — вам потребуется знание теории(хотя бы схематично…), как это можно сделать!

    Для того, чтобы заменить картинку в javascript надо заменить путь в теге картинки

    <img src=»

    здесь меняем содержание

    «>

    Скрипт замены картинки javascript .

    Далее нам нужен способ, с помощью которого, в реальном времени, т.е. при нажатии, — пусть это будет кнопка button произойдет замена содержания тега картинки на другой путь, к новой картинке. Для этого нам потребуется javascript

    Как обратиться к тегу картинки для замены.

    Чтобы заменить содержание атрибута src — надо, каким-то образом обратиться к тегу — там есть несколько способов сделать это!

    У нас заранее есть выбор, поэтому, мы добавим данному тегу, произвольный id, с произвольным значением : change_image

    <img id=»change_image» src=»

    здесь меняем содержание

    «>

    Пример замены пути картинки пример

    Как будем менять содержание тега src!?

    Сделаем стенд, на котором вживую покажем, как будет меняться картинка вслед за заменой содержимого внутри тега src

    Возьмем выше идущий код и прикрепим к нему кнопку, для смены пути картинки, нажмите по кнопке:

    <img id=»change_image» src=»

    здесь меняем содержание

    «>

  • Замена картинки по клику

    После того, как вы немного разобрались в теории(или просто прочитали) перейдем к созданию реального примера замены картинки по клику!

    Для этого вам понадобится:

    Картинка №1:

    Картинка №2:

    Тег img + в атрибут src помещаем адрес первой картинки + id, соберем код картинки:

    <img id=»change_image» src=»https://dwweb.ru/__img/php/img_php/morning.png»>

    Кнопка для замены картинки javascript :

    Далее, для того, чтобы произошла смена картинки в реальном времени, вам потребуется какой-то элемент, в нашем примере пусть это будет button.

    Добавляем в тег onclick.

    Используем один из способов обратиться к id, просто пишем «значение» атрибута id(change_image), поcле него точка, атрибут src, равно и в кавычках помещаем путь до второй картинки:

    onclick=»change_image.src=’https://dwweb.ru/__img/php/img_php/day.png’

    Соберем кнопку:

    <button onclick=»change_image.src=’https://dwweb.ru/__img/php/img_php/day.png'»>Смени содержание тега src</button>

    Соберем весь код:

    Код замены картинки по клику

    Описание всего кода замены картинки вы сделали, теперь соберем его:

    <img id="change_image" src="https://dwweb.ru/__img/php/img_php/morning.png">

    <button onclick="change_image.src='https://dwweb.ru/__img/php/img_php/day.png'">Смени содержание тега src</button>

    Пример замены картинки по клику

    Код «замены картинки по клику» картинки я вывел выше, теперь выведем данный код прямо здесь:

    Для смены изображения по клику по кнопке, нажмите Смени картинку javascript
    Пример замены картинки по клику

  • Простой слайдер на js

    Сделаем простой слайдер javascript, проще которого просто не существует! Я так думаю…

    Нам понадобится переменная, которая будет равна нулю с самого начала!

    var theNum = «0»;

    Нам понадобится массив с названием картинок, мы уже выше приводили пути до картинок, отличаются лишь названия внутри пути

    let arr = [«day», «evening», «morning», «night»];

    Напишем самую простую функцию смены картинки по нажатию, в первой строке, напишем условие, в том случае, когда значение переменной theNum будет равна количеству ячеек в массиве, то приравняем эту переменную к нулю!

    if(theNum == arr.length){theNum=»0″;}

    При каждом нажатии будем отправлять значение ячейки массива([theNum]) в путь картинки:

    change_image_1.src=’https://dwweb.ru/__img/php/img_php/’+arr[theNum]+’.png’;

    И в самом низу поставим счетчик нажатий, такая запись theNum++; равнозначна theNum = theNum + 1;:

    theNum++;

    Соберем нашу функцию:

    function myFOO()

    {

    if(theNum == arr.length){theNum=»0″;}

    change_image_1.src=’https://dwweb.ru/__img/php/img_php/’+arr[theNum]+’.png’;

    theNum++;

    }

    Итоговый скрипт, смены картинки вкруговую по нажатию

    <script>

      var theNum = «0»;

      let arr = [«day», «evening», «morning», «night»];

    function myFOO()

    {

      if(theNum == arr.length){theNum=»0″;}

      change_image_1.src=’https://dwweb.ru/__img/php/img_php/’+arr[theNum]+’.png’;

      theNum++;

    }

    </script>

    Далее нам понадобится кнопка с вызовом onclick нашей функции, о которой написали выше:

    <button onclick=»myFOO()» class=»button «>Смени картинку javascript</button>

    В данный скрипт, можно добавить любое количество картинок, просто складываем картинки в одну папку и в массив вписываем название картинки!

    Готовый результат: самый простой слайдер на javascript

    Простой слайдер на js

  • Слайдер с выбором следующей и предыдущей картинки

    Как сделать слайдер -смана картинки предыдущей на следующую и обратно!

    Нам понадобится опять тег картинки, но уже две кнопки — смена картинки на следующую, смена картинки на предыдущую:

    <img id=»change_image_2″ src=»https://dwweb.ru/__img/php/img_php/morning.png» >

    <button onclick=»go_to_left()» class=»button «>Показать предыдущую</button>

    <button onclick=»go_to_right()» class=»button» style=»float: right;»>Показать следующую</button>

    Сверху мы разобрали пример смены картинки по счету следующую! Нам остается скопировать эту функцию и заменить пару значений!

    Если картинка должна показываться предыдущая, значит будем отнимать(theNum—; ), как только дойдем до значения равным -1, то переменной theNum приравняем arr.length -1; — вопрос на засыпку — зачем отняли 1!?

    Соберем код смены картинки при клике на одну кнопку выбирается следующая картинка. при выборе кнопки предыдущая картинка — показывается предыдущая:

    var theNum = «0»;

    let arr = [«morning», «day», «evening», «night»];

    function go_to_right()

    {

      theNum++;

      if(theNum == arr.length){theNum=»0″;}

      change_image_2.src=’https://dwweb.ru/__img/php/img_php/’+arr[theNum]+’.png’;

    }

    function go_to_left()

    {

      theNum—;

      if(theNum == «-1»){theNum = arr.length -1; } console.log(theNum );

      change_image_2.src=’https://dwweb.ru/__img/php/img_php/’+arr[theNum]+’.png’;

    }

    Слайдер с выбором следующей и предыдущей картинки

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Javascript return error object
  • Internal error cannot find utcompiledcode record for this version of the uninstaller
  • Javascript error addlangkeys is not defined
  • Internal auth provider error cubixworld
  • Heather error scania

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии