Pass variable to this.src - javascript

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>

Related

How I can change this deprecated code document.write for improve pagespeed

I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>
There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);
the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.
Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

JS: How to change the image reference ending value

Instead of having a ton of if statements, I would like the method to display the correlated image by name, fx. clicking BlackPicture4.gif will turn it into WhitePicture4.gif. The number of the picture is passed on to the method.
I'm new to javascript, so maybe indexes[] don't work as I thought they do.
I have an array of Whitepicures:
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
...
function changePicture(int)
{
var image = document.getElementById('Img' + int); //works
image.src = imgArray[int] //doesn't work
var thefile = "imgArray" + int + ".gif" //also doesn't work
image.src = thefile;
}
I tried so many different ways, but could use help
html: //as requested, but that works fine
<img id="Img1" onclick="changePicture(1)" src="Blackpicture1.gif" width="50" height="50" >
<img id="Img2" onclick="changePicture(2)" src="Blackpicture2.gif" width="50" height="50" >
...
Edit: The problem is solved by adding .src to "= imgArray[int]"
Another thing I didn't think of was I had to assign the array elements INSIDE a function, rather than just on top of the file where I believe only declarations can be made.
This may work im not sure
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
var x;
function changePicture(x) {
var image = document.getElementById('Img' + x);
image.src = imgArray[x].src;
}
I think what you're trying to do might be
function changePicture(int){
document.getElementById('Img'+int+'').setAttribute('src',imageArray[int].src);
}
In this example, the pic with id='1' will be converted into a pic with id='2':
$("img").click(function() {
var x = $(this).attr("id");
x++;
var y = $("#" + x).attr("src");
$(this).html("");
$(this).html("<img src='" + y "'>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="pic1.jpg" id="1">
<img src="pictobereplaced.jpg" id="2">

Get Image Source URLs from a Different Page Using JS

Everyone:
I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.
Page 1 is just a page with images:
<html>
<head>
</head>
<body>
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</body>
</html>
Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)
<script type = "text/javascript">
var days = 730;
var rotator = new Object();
var currentTime = new Date();
var currentMilli = currentTime.getTime();
var images = [], index = 0;
images[0] = "image0.jpg";
images[1] = "image1.jpg";
images[2] = "image2.jpg";
images[3] = "image3.jpg";
rotator.getCookie = function(Name) {
var re = new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1];
return'';
}
rotator.setCookie = function(name, value, days) {
var expireDate = new Date();
var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}
rotator.randomize = function() {
index = Math.floor(Math.random() * images.length);
randomImageSrc = images[index];
}
rotator.check = function() {
if (rotator.getCookie("randomImage") == "") {
rotator.randomize();
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
if ( currentMilli > writtenTime + 10000 ) {
rotator.randomize();
var writtenImage = rotator.getCookie("randomImage")
while ( randomImageSrc == writtenImage ) {
rotator.randomize();
}
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenImage = rotator.getCookie("randomImage")
document.write("<img src=" + writtenImage + ">");
}
}
}
rotator.check()
</script>
Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.
Please let me know if I can clarify!
Try this.
<script>
$.get('http://path/to/page/1', function(data) {
var imgs = $('<div/>').html(data).find('img');
imgs.each(function(i, img) {
alert(img.src); // show a dialog containing the url of image
});
});
</script>
I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.
$.get('page1.html', function(data, status) { // get the page with the images
var parser = new DOMParser();
var xmldoc = parser.parseFromString(data, "text/html"); //turn it into a dom
var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
return img.src; //convert them to an array of sources
});
setInterval(function() { // run this every 10 seconds
var imags = document.getElementsByTagName('img'); // find the images on this page
Array.prototype.slice.call(imgs).forEach(function(img) {
var imgSrc = Math.floor(Math.random()*imageSrcs.length); //get a random image source
img.src = imageSrcs[imgSrc]; //set this image to the src we just picked at random
});
}, 10000);
}, 'html');
why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.
external.html
<html>
....
<div id="imgContainer">
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</div>
</html>
ajax.js
function ajaxContent(reg, extReg) {
var toLoad = 'external.html' + extReg;
function loadContent() {
$(reg).load(toLoad,'',getSrcPaths())
}
function getSrcPaths() {
$(reg + ' #image0').delay(200).fadeIn('slow');
$(reg + ' #image1').delay(200).fadeIn('slow');
// or however you want to store/display the images
}
}
Then onload just make a call to ajaxContent something like
<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
....
</body>
This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

Add link to image dynamically

If i have "img" element id = "myimg".
Is posible to add link to "img" without edit html page using jQuery
<img id="myimg" src="image.png">
I like to make "myimg" have link like this.
<img id="myimg" src="image.png">
You can use wrap():
$("#myimg").wrap("<a href='test.html'></a>');
or
$("#myimg").wrap($("<a>").attr("href", "test.html"));
or:
var a = $("<a>").attr("href", "test.html");
$("#myimg").wrap(a);
I am not into jQuery. Using Javascript, you can do something like:
var parentEl = document.getElementById("myimg").parentElement;
var imgEl = parentEl.innerHtml;
parentEl.innerHtml = '' + imgEl + '';
$(document).ready(function() {
var src = "linkhere.html";
var a = $("<a/>").attr("href", src);
$("#myimg").wrap(a);
});

Categories