Как изменить картинку при нажатии на кнопку

I have an image and when the image is clicked I want to reveal another image below it. I am looking for a simple CSS only solution. Is that possible?

TL;DR!

input[type="checkbox"] {
    content: url('http://placekitten.com/150/160');
    appearance: none;
    display: block;
    width: 150px;
    height: 150px;
}

input[type="checkbox"]:checked {
    content: url('http://placekitten.com/170/180');
}
<input type="checkbox" />

A Pure CSS Solution

Abstract

A checkbox input is a native element served to implement toggle functionality, we can use that to our benefit.

Utilize the :checked pseudo class — attach it to a pseudo element of a checkbox (since you can’t really affect the background of the input itself), and change its background accordingly.

Implementation

input[type="checkbox"]:before {
    content: url('images/icon.png');
    display: block;
    width: 100px;
    height: 100px;
}
input[type="checkbox"]:checked:before {
    content: url('images/another-icon.png');
}

Demo

Here’s a full working demo on jsFiddle to illustrate the approach.

Refactoring

This is a bit cumbersome, and we could make some changes to clean up unnecessary stuff; as we’re not really applying a background image, but instead setting the element’s content, we can omit the pseudo elements and set it directly on the checkbox.

Admittedly, they serve no real purpose here but to mask the native rendering of the checkbox. We could simply remove them, but that would result in a FOUC in best cases, or if we fail to fetch the image, it will simply show a huge checkbox.

Enters the appearance property:

The (-moz-)appearance CSS property is used … to display an element
using a platform-native styling based on the operating system’s theme.

we can override the platform-native styling by assigning appearance: none and bypass that glitch altogether (we would have to account for vendor prefixes, naturally, and the prefix-free form is not supported anywhere, at the moment). The selectors are then simplified, and the code is more robust.

Implementation

input[type="checkbox"] {
    content: url('images/black.cat');
    display: block;
    width: 200px;
    height: 200px;
    -webkit-appearance: none;
}
input[type="checkbox"]:checked {
    content: url('images/white.cat');
}

Demo

Again, a live demo of the refactored version is on jsFiddle.

References

  • :checked
  • -moz-appearance/-webkit-appearance

Note: this only works on webkit for now, I’m trying to have it fixed for gecko engines also. Will post the updated version once I do.

Update: the appearance property is now widely adopted, so the use of vendor prefixes is redundant. Horay!

I want to change an image to some other image when i click on the object. the code is stacked in the following order:

<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>

What I wish to do is, when I click on the <li> i want to change the image to a coloured version of the image, i.e. some other image. Now, I know I can use JQuery/JS to accomplish it. But I don’t want a huge amount of JS code to accomplish something so simple.

Can it be done using something simpler? Like pseudo selectors? .active class?

I cannot seem to think of it.

rubo77's user avatar

rubo77

18.9k30 gold badges130 silver badges220 bronze badges

asked Jul 20, 2011 at 16:06

amit's user avatar

1

To change image onclik with javascript you need to have image with id:

<p>
    <img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png" 
        style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"/>
</p>

Then you could call the javascript function when the image is clicked:

function changeImage() {
    if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
        document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
    } else {
        document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
    }
}

This code will set the image to maximize.png if the current img.src is set to minimize.png and vice versa.
For more details visit:
Change image onclick with javascript link

Dexter's user avatar

Dexter

7,2553 gold badges37 silver badges36 bronze badges

answered Sep 16, 2012 at 15:07

Markweb's user avatar

MarkwebMarkweb

2832 silver badges6 bronze badges

0

Or maybe
and that is prob it

<img src="path" onclick="this.src='path'">

answered Jan 4, 2017 at 11:37

anymousse's user avatar

anymousseanymousse

1611 silver badge2 bronze badges

0

How about this? It doesn’t require so much coding.

$(".plus").click(function(){
 $(this).toggleClass("minus")  ; 
})
.plus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}

.plus.minus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><div class="plus">CHANGE</div></a>

isherwood's user avatar

isherwood

56.5k16 gold badges109 silver badges151 bronze badges

answered Feb 14, 2017 at 12:41

Bel's user avatar

BelBel

1432 silver badges10 bronze badges

0

If your images are named you can reference them through the DOM and change the source.

document["imgName"].src="../newImgSrc.jpg";

or

document.getElementById("imgName").src="../newImgSrc.jpg";

answered Jul 20, 2011 at 16:11

Clayton's user avatar

ClaytonClayton

5,3101 gold badge18 silver badges15 bronze badges

The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you’ll need to use some JS.

I would name the images starting with bw_ and clr_ and just use JS to swap between them.

example:

$("#images").find('img').bind("click", function() {
  var src = $(this).attr("src"), 
      state = (src.indexOf("bw_") === 0) ? 'bw' : 'clr';

  (state === 'bw') ? src = src.replace('bw_','clr_') : src = src.replace('clr_','bw_');  

  $(this).attr("src", src);

});

link to fiddle: http://jsfiddle.net/felcom/J2ucD/

answered Jul 20, 2011 at 16:17

Collin G.'s user avatar

Collin G.Collin G.

4662 silver badges9 bronze badges

0

Here, when clicking next or previous, the src attribute of an img tag is changed to the next or previous value in an array.

<div id="imageGallery">    
    <img id="image" src="http://adamyost.com/images/wasatch_thumb.gif" />
    <div id="previous">Previous</div>    
    <div id="next">Next</div>        
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script>
    $( document ).ready(function() {

        var images = [
            "http://placehold.it/350x150",
            "http://placehold.it/150x150",
            "http://placehold.it/50x150"    
        ];

        var imageIndex = 0;

        $("#previous").on("click", function(){          
            imageIndex = (imageIndex + images.length -1) % (images.length);    
            $("#image").attr('src', images[imageIndex]);
        });

        $("#next").on("click", function(){
            imageIndex = (imageIndex+1) % (images.length);    
            $("#image").attr('src', images[imageIndex]);
        });

        $("#image").attr(images[0]);

    });
</script>

I was able to implement this by modifying this answer: jQuery array with next and previous buttons to scroll through entries

Community's user avatar

answered Mar 28, 2014 at 5:27

addzies's user avatar

If you don’t want use js, I think, you can use <a href="javascript:void(0);"></a> instead of img and then use css like

a {
  background: url('oldImage.png');
}
a:visited {
  background: url('newImage.png');
}

EDIT: Nope. Sorry it works only for :hover

answered Jul 20, 2011 at 16:15

Molecular Man's user avatar

Molecular ManMolecular Man

22.2k3 gold badges71 silver badges88 bronze badges

1

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

answered Jul 21, 2011 at 16:02

Andres Ilich's user avatar

Andres IlichAndres Ilich

75k21 gold badges156 silver badges138 bronze badges

This script helps to change the image on click the text:

<script>
    $(document).ready(function(){
    $('li').click(function(){
    var imgpath = $(this).attr('dir');
    $('#image').html('<img src='+imgpath+'>');
    });
    $('.btn').click(function(){
    $('#thumbs').fadeIn(500);
    $('#image').animate({marginTop:'10px'},200);
    $(this).hide();
    $('#hide').fadeIn('slow');
    });
    $('#hide').click(function(){
    $('#thumbs').fadeOut(500,function (){
    $('#image').animate({marginTop:'50px'},200);
    });
    $(this).hide();
    $('#show').fadeIn('slow');
    });
    });
    </script>


<div class="sandiv">
<h1 style="text-align:center;">The  Human  Body  Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>

Zoe stands with Ukraine's user avatar

answered Jan 9, 2017 at 6:27

M. Lak's user avatar

M. LakM. Lak

8959 silver badges17 bronze badges

function chkicon(num,allsize) {
    var  flagicon = document.getElementById("flagicon"+num).value;

    if(flagicon=="plus"){
         //alert("P== "+flagicon);

         for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }


         document.images["pic"+num].src = "../images/minus.gif";
         document.getElementById("flagicon"+num).value = "minus";

    }else if(flagicon=="minus"){
         //alert("M== "+flagicon);

          document.images["pic"+num].src  = "../images/plus.gif";    
          document.getElementById("flagicon"+num).value = "plus";

    }else{
          for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }
    }
}

Pang's user avatar

Pang

9,365146 gold badges85 silver badges121 bronze badges

answered Jun 17, 2015 at 7:20

Cherryishappy's user avatar

How can I swap an image’s SRC attribute, on click of that image?

<a href="#">
    <img src="./layout/images/search.png" />
</a>

$('img[src="./layout/images/search.png"]').click(function () {
    $(this).attr('src',"./layout/images/search_select.png")
});

Bill Keller's user avatar

asked Nov 26, 2011 at 9:37

user1065056's user avatar

You can try this solution:

$("img").click(function(){
   $(this).attr("src","new.gif");
})

As David Hedlund points out this will change all images on a page due to the img selector. You could target an image using a class as sam152 suggests or, you could target an image using it’s src attribute —

 $("img[src='old.gif']").click(function (){
   $(this).attr("src","new.gif");
})

See my demo — JSFiddle

Dino's user avatar

Dino

7,5099 gold badges42 silver badges78 bronze badges

answered Nov 26, 2011 at 9:41

ipr101's user avatar

ipr101ipr101

24k7 gold badges57 silver badges61 bronze badges

7

If you have an image with a class called ‘swap’, you can use the following snippet. It uses the click event, and then attr, to change the images src attribute.

$('.swap').click(function(){ 
    $(this).attr('src','new/path/to/img.jpg');
});

answered Nov 26, 2011 at 9:42

Sam152's user avatar

Sam152Sam152

19.1k13 gold badges59 silver badges78 bronze badges

1

How can I swap an image’s SRC attribute, on click of that image?

<a href="#">
    <img src="./layout/images/search.png" />
</a>

$('img[src="./layout/images/search.png"]').click(function () {
    $(this).attr('src',"./layout/images/search_select.png")
});

Bill Keller's user avatar

asked Nov 26, 2011 at 9:37

user1065056's user avatar

You can try this solution:

$("img").click(function(){
   $(this).attr("src","new.gif");
})

As David Hedlund points out this will change all images on a page due to the img selector. You could target an image using a class as sam152 suggests or, you could target an image using it’s src attribute —

 $("img[src='old.gif']").click(function (){
   $(this).attr("src","new.gif");
})

See my demo — JSFiddle

Dino's user avatar

Dino

7,5099 gold badges42 silver badges78 bronze badges

answered Nov 26, 2011 at 9:41

ipr101's user avatar

ipr101ipr101

24k7 gold badges57 silver badges61 bronze badges

7

If you have an image with a class called ‘swap’, you can use the following snippet. It uses the click event, and then attr, to change the images src attribute.

$('.swap').click(function(){ 
    $(this).attr('src','new/path/to/img.jpg');
});

answered Nov 26, 2011 at 9:42

Sam152's user avatar

Sam152Sam152

19.1k13 gold badges59 silver badges78 bronze badges

1

Как сделать смену картинки при клике?

Здравствуйте.
5b8d4c986ee55625726196.png
Есть основная картинка под ней дополнительные, как сделать, чтоб при клике на дополнительную она отображалась на главной? Сейчас доп.кртинки привязаны жестко по id в шаблоне id=»display-1″ на a href=»#display-1″
Я так понимаю это нужно ява скриптом делать?

<div class="col-md-5 col-sm-5 col-xs-12">
									<div class="clear"></div>
									<div class="tab-content">
										<!-- Product = display-1-1 -->
										<div role="tabpanel" class="tab-pane fade in active" id="display-1">
											<div class="row">
												<div class="col-xs-12">
													<div class="toch-photo">
														<a href="#"><img src="{{ product.images.url }}" data-imagezoom="true" alt="#" /></a>
													</div>
												</div>
											</div>
										</div>
										<!-- End Product = display-1-1 -->
									</div>
									<!-- Start Toch-prond-Menu -->
                                    {% for albom in albom %}
									<div class="toch-prond-menu">
										<ul role="tablist">
											<li role="presentation" class=" active"><a href="#display-1" role="tab" data-toggle="tab"><img src="{{ albom.image.url }}" alt="#" /></a></li>
										</ul>
									</div>
                                    {% endfor %}
									<!-- End Toch-prond-Menu -->
								</div>


  • Вопрос задан

    более трёх лет назад

  • 5561 просмотр

Пригласить эксперта

Вот есть «готовое» решение. kenwheeler.github.io/slick

Примените его, сами велосипед не пишите. Однако настоятельно рекомендую ознакомиться с исходным кодом, чтобы понимать, как подобные вещи пишутся.

Сам отвечу на свой вопрос, может кому то пригодится.
Подсказали на другом форуме. Можно сделать через этот яваскрипт

<script type="text/javascript">
 var img = document.getElementById("display-1").getElementsByTagName("img")[0]; //получаем большую картинку.
 function changeIMG(str){
    img.setAttribute('src', str);
 }
</script>

на <a> повесить обработчик onclick = "changeIMG('/новый адрес для картинки/')"

Все работает, картинки меняет так как нужно было.


  • Показать ещё
    Загружается…

10 февр. 2023, в 16:23

300 руб./за проект

10 февр. 2023, в 16:12

1000 руб./за проект

10 февр. 2023, в 16:11

50000 руб./за проект

Минуточку внимания

Слайдер 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’;

    }

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

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

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

  • Как изменить картинку при наведении html
  • Как изменить картинку при включении макбука
  • Как изменить картинку при наведении css
  • Как изменить картинку при включении компьютера windows 10
  • Как изменить картинку при звонке хонор

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

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