Title

Смена картинок по нажатии на кнопку?

Добрый день, подскажите как найти или сделать так, чтобы при нажатии на кнопку менялись картинки (их 3).
Например, пользователь видит 1 картинку прочитал на ней что-то нажал на кнопку и ту 1 картинку заменяет 2 фотография вновь прочитал что-то, нажал на кнопку и 2 фотографию заменяет 3.
из кода ничего особенного
snippet

Bukhanets

     
document.body.addEventListener('click', e => < if (!e.target.matches('button')) return document.querySelector('.pic img').src = e.target.dataset.src document.querySelectorAll('button').forEach(btn =>btn.classList.remove('active')) e.target.classList.add('active') >)

SPART4K

Сначала составляете массив из ваших картинок, туда вставляете пути к ним.
Далее объявляете кнопку и блок с картинкой куда будете вставлять путь
По клику на кнопку вставляете картинку и при каждом клике увеличиваете переменную на 1, если переменная равна или больше кол-во картинок — обнуляете
snippet

Источник

Как поменять картинки при клике на кнопку?

При клике на кнопку меняется картинка. Проблема в том что таких блоков может быть на странице много, а код применяется только к первому. Подскажите пожалуйста, как сделать так что-бы у каждого блока менялась своя картинка при клике на кнопку?
snippet

Простой 2 комментария

Ankhena

modelair

lina666

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

     .row < display: flex; flex-wrap: wrap; >.picture-block < flex: 0 0 50%; >.picture-block__img < width: 300px; height: 400px; >.button.--active  

Источник

JavaScript Change Image onclick Event

We are displaying the best method to JavaScript change image onclick event with the example. As well as, given another way to implement ‘change image on button click javascript’.

Also, We can do change image on mouse hover and mouse click event in the below section. After that, showing an example of change multiple image onclick.

javascript change image onclick event

JavaScript Change Image onclick Event

    h2 < text-align: center; font-size: 30px; >img#getImage < width: 300px; height: auto; border: 4px solid #a1a1a1; >div  

Change image onClick event here.

Here, the whole code of change image with onclick event. So, I am telling you about this code.

Firstly, we created an Html code structure and also, created an image tag and button in the body section.

Under, you can see this button and images code. After that, I have to add the image source path and put an id for getting the source code.

Thus, the Id name is getImage and image source name imageName1.

Afterward, added a script in the below code and apply function. Now, add function in the button tag which is name imagefun with onclick() event.

Now, about in the function getting image src by id using JavaScript document.getElementById().

So then, added an if the condition for change image onclick event. There are define two image source codes and change with onclick event.

Here, showing parts of implement to change multiple images. Firstly, the visible code of image and input button in the below section.

 

Change image onClick event here.

Under, This is Html code which we added in the body section as you saw.

Secondly, Displaying JavaScript code after the Html code. You can see above an example.

Additionally, we created some implement for design structure to better show image and button on the front end. So, This is a stylesheet in the below code.

Here, these are some methods to get elements using JavaScript.

Replace Image on Button Click JavaScript

Similarly, you can use for change image on button click using javascript. therefore, we have provided an example in the below area.

 

Change image onClick event here.

So, you can change only one line from the Html code. Likewise, replace the input tag to button this is the main code line.

After that, all codes same as above we define script code. you might add a script tag with function.

Replace Picture onclick CSS

Similarly, you can use CSS in our Html code. I already defined style with onclick() event. Also, change image size and button design.

As well as, showing alignment you can copy this code which we provided above area.

Hence, you can add another CSS design that you want on your page. There have many components to relate your CSS style.

how to change image on mouse click in javascript

How to Change Image on Mouse Click in JavaScript

    h2 < text-align: center; font-size: 30px; >img#getImage < width: 300px; height: auto; border: 4px solid #a1a1a1; >div  

Change image onClick event here.

Here, we add a mouse hover event. When you click and want to change image going to on image through the mouse.

Then, automatically change the image on the mouse click event. So, you can use this code

otherwise, added only this line, and remove old input and button code from your editor.

JavaScript Change Multiple Images onclick

Hence, there are we implement two images to change. Therefore, it means you can add more images to change multiple images of onclick events.

Now, given an example for change multiple images using on click event check below code.

As an example, we added another image source with script code. Afterward, displaying multiple images from these codes. You can add more images as you want on your page.

Conclusion

Finally, you saw many methods to JavaScript change image onclick event. Also, if you have any other queries you can ask us. Here this is the main point for change image with onclick event using JavaScript.

Источник

Смена картинки при нажатии

Доброго времени суток!
Хочу с помощью JS сделать так,чтобы при клике мышкой менялась картинка.
Пробую несколько вариантов:
1.

function my_click(){document.getElementById('image').innerHTML='pic';}
img id="image" src="2.jpg" alt="The Beatles" onClick="my_click();">
var mimg=document.createElement("img"); mimg.setAttribute('src', "3.jpg"); function my_click(){document.getElementById("image").innerHTML="mimg";}
img id="image" src="2.jpg" alt="The Beatles" onClick="my_click();">
var NewImg = new Image (); NewImg.src = '3.jpg'; function my_click(){document.getElementById("image").innerHTML="NewImg";}
img id="image" src="2.jpg" alt="The Beatles" onClick="my_click();">

Ничего не работает. Я JS только начала изучать, идет тяжеловато(((
Хочется сделать через innerHTML

Добавлено через 49 минут
Всё! Нашла решение!

function my_click() { document.getElementById("image").src="4.jpg"; };
img id="image" src="2.jpg" alt="The Beatles" onclick="my_click();">

Смена картинки при нажатии
Есть форма,которая меняет картинку при клике. <img src="box.jpg" onclick=’this.src="lut_1.jpg"’.

Смена картинки при нажатии
В общем задача довольно проста(как мне казалось). Генерация 2 случайных карт их колоды. Карты.

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

Смена картинки при нажатии input radio
Доброго времени суток! Есть две кнопки <input type="radio" value="0".

Источник

Читайте также:  PDF in HTML
Оцените статью