How i show image src on click - javascript

Write a function that will be called upon pressing the right button of one of the images you have on the site.
The function calls up a confirm () window in which you ask the user if he wants to know the source of the image
If the user clicks OK alert (this.src), which shows the content of the src attribute of that image
If the user clicks on cancel, disable the context menu that appears at
pressing the right button
this is my wrong code
<img src="opera1.png" id="immagine1" alt="immagine1" width="500" height="333" oncontextmenu="destra()">
<img src="ioaparatissima.JPG" id="immagine2" alt="immagine2" width="500" height="333" oncontextmenu="destra()">
javascript
function destra(){
var r = confirm("Vuoi conoscere la src dell'immagine");
if(r == true) {
alert(y.src);
} else {
}
}

Since you are using inline event bindings I would suggest two changes.
oncontextmenu="destra(this)"
Pass in the element that the inline event binding is on.
function destra(y){
var r = confirm("Vuoi conoscere la src dell'immagine");
if(r == true) {
alert(y.src);
} else {
}
}
Accept the element as a method argument.

By rereading your statement it seems to me that this answer corresponds better ... (?)
document.querySelectorAll('img').forEach(el=> el.addEventListener('contextmenu',destra) )
function destra(e)
{
e.preventDefault() // disable real context Menu
if ( confirm("Vuoi conoscere la src dell'immagine") )
{
alert( this.src )
}
}
<img src="https://picsum.photos/150" alt="immagine1" >
<img src="https://picsum.photos/100" alt="immagine2" >

Use the getElementById(), like in this example:
function destra() {
let r = confirm("Vuoi conoscere la src dell'immagine?");
let y = document.getElementById("immagine1");
if (r == true) {
alert(y.src);
}
}

try like this... I hope this one usefull...
<img src="opera1.png" id="img1" alt="immagine1" width="500" height="333">
<button onclick="getimgId(1)">copy link</button>
<br/>
<img src="ioaparatissima.JPG" id="img2" alt="immagine2" width="500" height="333">
<button onclick="getimgId(2)">copy link</button>
<script type="text/javascript">
function getimgId(img_id){
var res = confirm("Vuoi conoscere la src dell'immagine");
if(res == true) {
var img_id = img_id;
var img_url = document.getElementById('img'+img_id).src;
alert(img_url);
} else {
}
}
</script>
now you want to just give unique id to images and there right side buttons of images...
like img1, img2, img3 for images and onclick="getimg(1)", getimg(2), getimg(3)...
you can easily assign unique ids using Javascript. just apply loop and inside the loops add imgs with unique ids...
for assign unique I share example below...below code is just for Your Reference. do changes as per your needs. you can search on google for more examples.
for(var i=0;i<yourRecordArray.length;i++){
newList = document.createElement('li');
newList.className = 'list-border';
newList.id = 'imgdiv'+i;
newList.innerHTML = '<img src="" id="img'+i+'">+
'<button onclick="">';
document.getElementById('add').appendChild(newList);

i solved like this
function destra(y) {
window.addEventListener("contextmenu", function(e){e.preventDefault();}, false);
var r = confirm("do you want to know the src of the image?");
if(r == true) {
alert(y.src);
} else {
}
}
<img src="https://picsum.photos/150" alt="immagine1"id="immagine1" alt="immagine1" width="150" height="150" oncontextmenu="destra(this)">
<img src="https://picsum.photos/150" alt="immagine2" id="immagine2" alt="immagine2" width="150" height="150" oncontextmenu="destra(this)">

Related

If/else statement with change image function not working for multiple images

I am very new to javascript and am in need of some help. My goal is to have 3 before photos that you click on to reveal the after photo (dog grooming website). With only one before/after photo the code works fine but with all 3 only the last one functions properly. Any ideas as to what I am doing wrong? If/else statements are still very new for me and not sure if I am using them properly.
<p>Click the dog to <br>show their transformation.</p>
<img id="dog1" onclick="changeImage()" src="images/dog1before.PNG" width="300" >
<br>
<img id="dog2" onclick="changeImage()" src="images/dog2before.PNG" width="300" >
<br>
<img id="dog3" onclick="changeImage()" src="images/dog3before.PNG" width="300" >
<script>
//dog1 before and after
function changeImage() {
var image = document.getElementById("dog1");
if (image.src.match("dog1after")) {
image.src = "images/dog1before.PNG";
} else {
image.src = "images/dog1after.PNG";
}
}
//dog2 before and after
function changeImage() {
var image = document.getElementById("dog2");
if (image.src.match("dog2after")) {
image.src = "images/dog2before.PNG";
} else {
image.src = "images/dog2after.PNG";
}
}
//dog3 before and after
function changeImage() {
var image = document.getElementById("dog3");
if (image.src.match("dog3after")) {
image.src = "images/dog3before.PNG";
} else {
image.src = "images/dog3after.PNG";
}
}
</script>
The onclick callback function names are the same, try changing them to changeImageA, changeImageB and changeImageC or something.
Once you have that it would be better to use a single function, pass in an argument and do a switch statement or if/else to change the image depending which one was clicked.
Use one function for all images:
<p>Click the dog to <br>show their transformation.</p>
<img id="dog1" onclick="changeImage()" src="images/dog1before.PNG" width="300" >
<br>
<img id="dog2" onclick="changeImage()" src="images/dog2before.PNG" width="300" >
<br>
<img id="dog3" onclick="changeImage()" src="images/dog3before.PNG" width="300" >
<script>
function changeImage(event) {
var image = document.getElementById(event.target.id);
if (image.src.match("after")) {
image.src = "images/" + event.target.id + "before.PNG";
} else {
image.src = "images/" + event.target.id + "after.PNG";
}
}
</script>
Here's a simple approach using the dataset:
<script>
function changeImage(elm) {
var after = elm.dataset.after;
var src = elm.getAttribute('src');
if (after && src !== after) {
elm.setAttribute('src', after);
}
}
</script>
<img src='images/dog1before.PNG' data-after='images/dog1after.PNG' onclick='changeImage(this);' />
<img src='images/dog2before.PNG' data-after='images/dog2after.PNG' onclick='changeImage(this);' />
<img src='images/dog3before.PNG' data-after='images/dog3after.PNG' onclick='changeImage(this);' />

Pass variable to this.src

I have the name of an image file generated in javascript and passed to the src of an image in HTML - this currently works.
I want to pass another image file as the onmouseover attribute of the image.
(because my file name is dynamically generated I can't use hover in css).
var new_source_for_image = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + ".png";
});
});
</script>
{/literal}
<div id="visit_daynight">
<div class="change_visit">
<img id="visit_image" src="" width="350" height="350">
</div>
</div>
So i thought of adding another variable from a generated file name:
var new_source_for_image_with_glow = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + "_glow" + ".png";
and:
<a href="#"><img id="visit_image" src="" width="350" height="350"
onmouseover="this.src=???"
onmouseout="this.src=???"></a>
But I don't know how to pass my new variable in the this.src attribute.
Anybody have any ideas?
Much appreciated!
I believe this is what you're looking for. No jQuery required just plain old JavaScript.
const image = document.querySelector('img');
const baseImagePath = 'https://unsplash.it/';
const mouseEnterImage = '300';
const mouseLeaveImage = '400';
const replaceImage = (withImg) => {
image.src = `${baseImagePath}${withImg}`;
}
document.addEventListener('mouseenter', () => replaceImage(mouseEnterImage));
document.addEventListener('mouseleave', () => replaceImage(mouseLeaveImage));
Here is a fiddle of it working: https://jsfiddle.net/dkbewvay/
Hope this helps.
this will work:
<script>
var new_source_for_image_with_glow = "testA.png";
var anotherSrc = "testB.png";
function onmouseoverFunc(element) {
element.src = new_source_for_image_with_glow;
}
function onmouseoutFunc(element) {
element.src = anotherSrc;
}
</script>
<a href="#">
<img id="visit_image" src="new_source_for_image_with_glow" width="350" height="350"
onmouseover="onmouseoverFunc(this)"
onmouseout="onmouseoutFunc(this)">
</a>
If you can dynamically set a src... I suppose you also can set a data attribute for an "alternate source" ?!?
// Simulating your dynamic file source for the image.
$("#visit_image").attr("src", "http://lorempixel.com/400/200/sports");
// The same way, you could set an "alternate source"...
$("#visit_image").data("altSrc", "http://lorempixel.com/400/200/animals");
// The mouse events handler
$("#visit_image").on("mouseenter mouseleave", function(){
var src = $(this).attr("src");
var altSrc = $(this).data("altSrc");
// Interchange the urls
$(this).attr("src", altSrc).data("altSrc", src);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="visit_daynight">
<div class="change_visit">
<img id="visit_image" src="" data-altSrc= "" width="350" height="350">
</div>
</div>
This demo interchanges the URL between "sports" and "animals".
With jQuery by using mouseover() and mouseout() and attr() methods.
$(document).ready(function(){
var file_name='your_file_name';
var new_source_for_image ="/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + ".png";
var new_source_for_image_with_glow = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + "_glow" + ".png";
$("img#visit_image").attr('src',new_source_for_image);
$("img#visit_image").mouseover(function(){
$(this).attr('src',new_source_for_image_with_glow);
});
$("img#visit_image").mouseout(function(){
$(this).attr('src',new_source_for_image);
});
});
the better way to use these event handlers, onmouseover & onmouseout is to supply them with their respective functions defined inside the your script. And you also need to properly assign the image to img element (ev.srcElement) Have a look:
<script>
MouseOverHandler = function(ev){
ev.srcElement.src = new_source_for_image
console.log('should change',ev);
}
MouseOutHandler = function(ev){
ev.srcElement.src = old_source_for_image
console.log('should change',ev);
}
</script>
<a href="#"><img id="visit_image" src="" width="350" height="350"
onmouseover="MouseOverHandler(this)"
onmouseout="MouseOutHandler(this)"></a>

Check if image source is equal to an image

My current code exists as:
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
function pictureChange(){
if(fixedScreenimg.src == "img/homeScreen.png"){
document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg");
}else{
document.getElementByID("fixedScreenimg").src="img/homeScreen.png");
}
}
</script>
As you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.
I've attempted to use getAttribute and the like.
Any pointers?
Thanks.
Few errors:
ID instead of Id in getElementById function.
Two, unnecessary closing brackets inside if condition.
var elem = document.getElementById('fixedScreenimg'),
btn = document.getElementById('btn');
function pictureChange() {
if (elem.src == "img/homeScreen.png") {
document.getElementById("fixedScreenimg").src = "img/fixedScreen.jpg";
} else {
document.getElementById("fixedScreenimg").src = "img/homeScreen.png";
}
console.log(elem.src);
}
btn.addEventListener('click', pictureChange);
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<button id='btn'>Change src</button>
You actually are adding a closing bracket )
Try the following:
function pictureChange(){
var elem = document.getElementById("fixedScreenimg");
if(elem.src === "img/homeScreen.png"){
elem.src="img/fixedScreen.jpg";
}else{
elem.src="img/homeScreen.png";
}
}
first declare what is fixedScreenimg and the brackets at the 2 statements
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
function pictureChange(){
var fixedScreenimg = document.getElementById("fixedScreenimg");
if(fixedScreenimg.src == "img/homeScreen.png"){
fixedScreenimg.src="img/fixedScreen.jpg";
}else{
fixedScreenimg.src="img/homeScreen.png";
}
}
</script>
Try with single line if condition
function pictureChange() {
var elem = document.getElementById("fixedScreenimg");
elem.src = (elem.src == "img/homeScreen.png") ? "img/fixedScreen.jpg" : "img/homeScreen.png";
}
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
You added a bracket at the end of your lines
document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg";

How to listen for changes to a img title attribute?

I have a img tag. On click, my CMS adds or removes the post from a favorites area. When the post is not in favorites, the img looks like:
<img src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
When I click on it, the img looks like:
<img src="minus_fav.png" onclick="doFavorites('5', 'minus'); return false;" title="Remove from favorites">
I want to listen for changes for title attribute and write that into some <div id="some-id"></div>. If I have an img with a title="Add to favorites" my code will be like the following after document.ready is fired:
<div id="some-id">Add to favorites</div>
<img src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
When I change the favorite status, the code will be:
<div id="some-id">Remove from favorites</div>
<img src="minus_fav.png" onclick="doFavorites('5', 'minus'); return false;" title="Remove from favorites">
I'm looking for something like .change() but that tracks the title attribute.
Lets do it! :)
This code will work if you have just 2 options (2 kinds of title text - Add to favorites and Remove from favorites)
At first we take to var current title of image
var newTitle = $(".someclass img").attr('title'); // .someclass mean your img parent element class
At document ready append title to your #some-id.
titleChange();
function titleChange() {
$("#some-id").html(newTitle);
}
And then we need to catch click on img and change our newTitle in the opposite value of title.
$(".someclass img").click(function() {
newTitleHolder = $(this).attr('title');
if(newTitleHolder == 'Add to favorites') {
newTitle = 'Remove from favorites';
}else {
newTitle = 'Add to favorites';
}
titleChange();
});
Thats all.
And if you have a lot of images on page with same parent class - just put this code into .each() function.
<img id="img" src="plus_fav.png" onclick="doFavorites('5', 'plus',$(this)); return false;" title="Add to favorites">
<img src="minus_fav.png" onclick="doFavorites('5', 'minus',$(this)); return false;" title="Remove from favorites">
function doFavorites(a,b,c)
{
if(b=='plus')
{
$('#some-id').text('Remove from favorites');
c.attr('title','Remove from favorites');
c.attr('src','minus_fav.png');
c.attr('onclick','doFavorites('5', 'minus',$(this))');
}else if(b=='minus')
{
$('#some-id').text('Add to favorites');
c.attr('title','Add to favorites');
c.attr('src','plus_fav.png');
c.attr('onclick','doFavorites('5', 'plus',$(this))');
}
}
If you want to listen to attribute, there is no direct way, but you can create a watcher that will check every for value and notify if value has updated.
Note: If you have a lot of images, on which you want to watch, this might have performance impact.
Code
JSFiddle
var originalTitle = "";
var count = 0;
var watchInterval = null;
function updateTitle() {
originalTitle = $("#img").attr("title");
console.log("Updating Title")
$("img").attr("title", "New Title " + count++);
if (count > 5) {
console.log("Clearing all intervals")
window.clearInterval(watchInterval)
}
watcher(updateOriginalTitle);
}
function updateOriginalTitle() {
originalTitle = $("#img").attr("title");
}
function watcher(callback) {
var watchInterval = setInterval(function() {
var currTitle = $("#img").attr("title");
if (currTitle != originalTitle) {
console.warn("Title has changed");
if (callback && typeof(callback) === "function")
callback();
}
}, 1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="test.jpg" id="img" title="test Image" onclick="updateTitle()">;
I didn't understood very well...
But i think you want to: Everytime that the title changes it writes a "log".
I'd do:
First identify the img.
<img id="img" src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
And then:
$(function(){
$(document).on("change","#img",function(){
var title = $(this).attr('title');
$('#some-id').append(title);
});
});

Javascript to image cycle

Simple request, but I don't know how to do it. I've got a series of 10 images (image0.gif, image1.gif image2.gif etc...) that need to change to the next image in the sequence (cycling around after 9) when another image is pressed. This is what I have so far...
<html>
<head></head>
<body bgcolor="#808080">
<script type="text/javascript">
var c = 0;
function preload(img) {
var a = new Image();
a.src = img;
return a;
}
if (needed) {
time0 = preload("image0.gif");
time1 = preload("image1.gif");
time2 = preload("image2.gif");
time3 = preload("image3.gif");
time4 = preload("image4.gif");
time5 = preload("image5.gif");
time6 = preload("image6.gif");
time7 = preload("image7.gif");
time8 = preload("image8.gif");
time9 = preload("image9.gif");
}
function clickme() {
// update image
c += 1;
// alert(c)
}
</script>
<div align="center">
<center>
<img src="images/image0.gif" width="20" height="55" name="time0"> <a href="#" onMouseDown="return clickme()">
<img src="images/button.gif" border="0" width="96" height="55">
</a>
</td>
</tr>
</table>
</center>
</div>
</body>
</html>
First, you can and should take advantage of the fact, that only thing diferrent in the each umage name is number. So, you can store number and create any image name:
function getImage(id) {
return "image"+id+".gif";
}
Then, you should have a way to acces the image that you want to change. Like adding id to he element:
<img id="changing" src="image0.png" />
There should be onclick used, not onmousedown. User may change his mind and hower the mouse away - that is not click:
<a href="#" onclick="clickme()" />
Finally, changing the image element:
var c=0;
var max = 9;
function clickme() {
c++;
if(c>max)
c=0; //looping back to zero
docment.getElementById("changing").src = getImage(c); //getImage is defined above
}
Put an id on the image (the-image, for instance).
function clicme() {
c += 1;
document.getElementById('the-image')
.setAttribute('src', 'image' + (c % 10) + '.gif');
}
Also there is no href element. I think you meant to type <a href.

Categories