JS: How to change the image reference ending value - javascript

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">

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>

Trying to grab a random pic through JS but dosen't work properly

Hi guys I am a django developer and trying to grab a random img through JS in html like below
img works and it would randomly pick one from the ImageArray.
However, the path will be <img src= '/static/%22%20%2B%20img%20%2B%22'>.
Rather than something I want like <img src= "{% static 'img/indexBg_1.png' %}" >
And the error msg is : GET http://192.168.7.64:8000/static/img/%22%20%2B%20pic%20%2B%20%22%20 404 (Not Found)
Could anyone enlighten me to resolve this problem? Thx!
<script type="text/javascript">
window.onload=function(){
ImageArray = new Array();
ImageArray[0] = 'img/indexBg_1.png';
ImageArray[1] = 'img/indexBg_2.png';
ImageArray[2] = 'img/indexBg_3.png';
var num = Math.floor( Math.random() * 3);
var img = ImageArray[num];
var path = " <img src= '{% static '" + img +"'%}'>"
console.log(img)
console.log(path)
}
</script>
if you want the path, it should be something like:
var path = window.location.href +'/static/'+ img;
but if you want to add image with that path inside div:
var element = document.getElementById("div1");
element.innerHTML=`<img src=${path} />`;
even better to do:
var path = window.location.href +'/static/'+ img;
var myimg = document. createElement("img");
myimg.src = path;
var element = document.getElementById("div1");
element.appendChild(myimg);

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>

Get multiple elements same class - JavaScript (getElementsByClass)

I have an 'a href' that is a title.
Vendor1 product title
I want to display an image based on the first word of the title.
Vendor1 product title
<div class="logo"></div>
Vendor2 product title
<div class="logo"></div>
Vendor3 product title
<div class="logo"></div>
These are item cells and they use the same template to be generated so the classes are always the same. There are many of them.
The script I have so far is working but only for the first product in the list (shows correct logo).
function getlogo() {
var string1 = document.getElementsByClassName('title')[0].innerHTML;
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
document.getElementsByClassName('logo')[0].innerHTML = '<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">';
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
}
getlogo();
I've looked around but sure how to loop this or even if that is the solution.
http://jsfiddle.net/W7bm5/
It's easy if you use jQuery each function.
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
$(this).html('<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
or you can do it with the pure javascript, but put your logics in a loop, with [0] replaced to the loop index.
Update - here's how to keep the current text links:
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
var html = $(this).parent().html();
$(this).parent().html(html + '<br /><img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
You could use a for loop to run through the code you have for a different index of the getElementsByClassName results. See your jsFiddle
You could also ditch the getElementByClassName, which I think has spotty support in some browsers and isn't especially good performance, and navigate the DOM using JavaScript if your structure is always the same, or even jQuery if you'd like a library to make it easier.
But by far the best is if you did it when it was generated in the first place. How are you generating the code and could you not use that to achieve what you are trying to achieve?

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.

Categories