JavaScript Toggle Image by clicking on Img - javascript

Im trying to toggle between two images but need the js to work with many different images. How do I make it with a parameter with the id? This is what I got so far:
JS
function changeIt(id)
{
var theImg = document.getElementsByTagName('img')[0].src;
var x = theImg.split("/");
var t = x.length-1;
var y = x[t];
if(y=='red.gif')
{
document.images.boxcolor1.src='./pics/green.gif'
}
if(y=='green.gif')
{
document.images.boxcolor1.src='./pics/red.gif'
}
}
HTML
<img src='./pics/green.gif' name='boxcolor1' id='boxcolor1' border='0' />
<img src='./pics/green.gif' name='boxcolor2' id='boxcolor2' border='0' />
<img src='./pics/green.gif' name='boxcolor3' id='boxcolor3' border='0' />
As you can see now it only works for the first image (boxcolor1).. I want it to work for all images by the name or id tag.
Thanks for all the help!

Try:
function changeIt(id)
{
var theImg = document.getElementById(id),
x = theImg.src.split("/"),
t = x.length-1,
y = x[t];
if(y == 'red.gif')
{
theImg.src='./pics/green.gif'
}
if(y == 'green.gif')
{
theImg.src='./pics/red.gif'
}
}
Working example:
http://jsbin.com/ugofiz/edit

Related

What is the best way to change images based on the last 3 characters on the URL?

What is the best way to change images based on the last 3 characters on the URL?
I have 3 pictures but when click - needs to stay as the selected image,
but the page refreshes and goes back to original image
<script type="text/javascript">
function image_swap() {
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3)
if (URLChar("NSW"); image.src = "../MCFILES/NSW1.jpg"
if (URLChar("VIC"); image.src = "../MCFILES/VIC1.jpg"
if (URLChar("QLD"); image.src = "../MCFILES/QLD1.jpg"
} else {
image.src = "../MCFILES/NSW1.jpg"
}
}
function newDocNSW() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=NSW");
}
function newDocQLD() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=QLD");
}
function newDocVIC() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=VIC");
}
</script>
<body>
This is the images i need to change when on hover and when click
runs another script to change URL.
When the page refreshes i need the option to have change picture
when page refreshes to change the URL
<img id="image_swap" src="../MCFILES/NSWO.jpg"
onclick="newDocNSW()"
onmouseover="this.src='../MCFILES/NSW1.jpg';"
onmouseout="this.src='../MCFILES/NSWO.jpg';">
<img id="image_swap" src="../MCFILES/QLDO.jpg"
onclick="newDocQLD()"
onmouseover="this.src='../MCFILES/QLD1.jpg';"
onmouseout="this.src='../MCFILES/QLDO.jpg';">
<img id="image_swap" src="../MCFILES/VICO.jpg"
onclick="newDocVIC()"
onmouseover="this.src='../MCFILES/VIC1.jpg';"
onmouseout="this.src='../MCFILES/VICO.jpg';">
</body>
</html>
This line will only extract a single character
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3 )
If you want the last three characters then use this:
var URLChar = $(location).attr('href').substring($(location).attr('href').length - 3, $(location).attr('href').length);
A much simpler plain/vanilla JavaScript approach would be:
var URLChar = location.href.substring(location.href.length - 3, location.href.length);
Your if conditions are also syntactically incorrect. Here's how it should be:
if (URLChar === "NSW"){
image.src = "../MCFILES/NSW1.jpg";
} else if (URLChar === "VIC"){
image.src = "../MCFILES/VIC1.jpg";
} else if (URLChar === "QLD"){
image.src = "../MCFILES/QLD1.jpg";
} else {
image.src = "../MCFILES/NSW1.jpg";
}
I think this should do if I'm understanding the problem correctly.

How do I change an image with javascript without an onclick event?

I'm trying to get a dummy username and profile picture to display at random, at a random interval. I also want the usernames to match their respective profile pictures.
I currently I have html that displays the usernames correctly
<p id="usr"></p>
<img id="changeimage" src="" alt="Profile picture">
And javascript like this
var players = ['player1', 'player2', 'player3']
var playerpics = ['player1.jpg', 'player2.jpg', 'player3.jpg'];
var activeuser;
var playerpicker = function (activeuser) {
usr.innerHTML = players[activeuser];
changeimage.innerHTML = "<img src='" + playerpics[activeuser] + "' />";
};
setInterval(function () {
var oneintwelve = Math.floor(Math.random() * 12);
if (oneintwelve === 3) {
activeuser = Math.floor(Math.random() * 3);
playerpicker(activeuser);
};
}, 1000);
I know I'm doing something wrong with implementing the new IMG tag, forgive me if I'm not doing this the best way, I'm fairly new to this. Thanks for the help.
You're almost there, you can change the src attribute of an image. Also you didn't quite correctly selected the elements.
var playerpicker = function (activeuser) {
document.getElementById("usr").innerHTML = players[activeuser];
document.getElementById("changeimage").src= playerpics[activeuser];
};
Check this link, it will help you learn http://www.w3schools.com/jsref/dom_obj_select.asp

trying to dynamically replace the url from "a href" but javascript is not updating results

I'm trying to replace the urls in the html using javascript but it is not working although when I test it by I "alerting" them the values pop up correctly, but when I publish it and click on the images the new urls are not applied. Any help would be greatly appreciated
Could you please look at the code and tell me what is going on?:
<script>
var rutaBase = "assets/fotos/";
function cambieFotos(cualFoto) {
var listaFotos = ["360.jpg", "foto3.jpg", "mathura.jpg"];
var numFotosLista = listaFotos.length;
var foto1 = document.getElementById("foto1");
var foto2 = document.getElementById("foto2");
var foto3 = document.getElementById("foto3");
for (i = 0; i < 3; i++) {
var fotoAleatoria = listaFotos[Math.floor(Math.random() * numFotosLista)];
var fotoRoll = document.getElementById("foto" + (i + 1));
fotoRoll.src = "assets/fotos/" + fotoAleatoria;
fotoRoll.href = "assets/fotos/" + fotoAleatoria; //this code is not working.
var sacarFotoLista = listaFotos.indexOf(fotoAleatoria);
listaFotos.splice(sacarFotoLista, 1);
numFotosLista = listaFotos.length;
}
}
</script>
<div id="contenedor">
<img id="foto1" onMouseOver="cambieFotos(this)" src="assets/fotos/360.jpg"> <--!this needs to update-->
<img id="foto2" onMouseOver="cambieFotos(this)" src="assets/fotos/foto3.JPG"><--!this needs to update-->
<img id="foto3" onMouseOver="cambieFotos(this)" src="assets/fotos/mathura.jpg"><--!this needs to update-->
</div>
<!--contenedor-->
fotoRoll is an <img>, not the surrounding <a>. You should modify the parent instead:
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;
You're setting the href on the image element, not the hyperlink element. Try something like
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;

Display random image with fitting link

I'm using the below code to show random images which works fine. How can I add to this code so that each image gets it's own link? I.e. if "knife.png" is randomly picked I want it to have a link that takes the user to "products/knife.html" and so on.
Thanks for any help!
<div id="box">
<img id="image" /></div>
<script type='text/javascript'>
var images = [
"images/knife.png",
"images/fork.png",
"images/spoon.png",
"images/chopsticks.png",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
Generalize your list of images so that that it can be multi-purposed - you can add additional information later. Then surround the image by an anchor tag (<a>) and use the following.
<div id="box">
<a name="imagelink"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images = ["knife","fork","spoon","chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "images/"+images[x]+".png";
document.getElementById('imagelink').href="products/"+images[x]+".html";
}
</script>
randImg();
Try doing something like this example. Like all these other guys have said, it's better to store this info in a database or something, but to answer your question, put the values you need into an object in the array and reference the properties of the object instead of just having a string array.
<div id="box">
<a id="a"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"http://www.dansdata.com/images/bigknife/bigknife1280.jpg", Href:"http://reluctantgourmet.com/tools/cutlery/item/267-chefs-knife-choosing-the-right-cutlery" },
imageUrlPair = { ImgSrc:"http://www.hometownsevier.com/wp-content/uploads/2011/01/fork.jpg", Href:"http://eofdreams.com/fork.html" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/9/92/Soup_Spoon.jpg", Href:"http://commons.wikimedia.org/wiki/File:Soup_Spoon.jpg" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/6/61/Ouashi.jpg", Href:"http://commons.wikimedia.org/wiki/Chopsticks" },
]
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;
}
randImg();
</script>
Surround the img with an a
<img id="image" />
Then add
document.getElementById("link").href = images[x].replace(".png",".html");
The .replace is a bit crude, but you get the idea.
You can use a convention based approach. In this case the convention is that each product, will have an associated image at "/image/[product]/.png" and a page at "products/[product].html"
<div id="box">
<a id="link"><img id="image" /></a></div>
<script type='text/javascript'>
var products = [
"knife",
"fork",
"spoon",
"chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "/images/" + products[x] + ".png";
document.getElementById('link').setAttribute("href", "products/" + products[x] + ".html");
}
randImg();
this is a very naive approach that won't scale very well. for example, if you have a list of products that changes frequently, or, you need to keep track of the number of available units. a more robust approach would be to store information about your products in a database, and a page that displays the data about a given product (a product detail page), and then use a data access technology to fetch a list of products for display in a product list page (similar to what you have here, except the list of products isn't hardcoded) and then each product would link to the product detail page.

Need to change an image href rollover effect into a td onclick

I am not an experienced javascript, css coder so I would appreciate as much help as possible. I've read some other posts for more understanding; they mentioned jquery but I'm not sure how to go about that either.
I have a code that was generated for me with a program. I need to change about 7 image buttons (not links) href rollovers into td onclick. Thanks so much in advance. Here is my current code:
Within the head -
<script type="text/javascript">
function newImage(arg) {
if (document.images) {
rslt = new Image();
rslt.src = arg;
return rslt;}
}
function changeImages() {
if (document.images && (preloadFlag == true)) {
for (var i=0; i<changeImages.arguments.length; i+=2) {
document[changeImages.arguments[i]].src = changeImages.arguments[i+1];}
}
}
var preloadFlag = false;
function preloadImages() {
if (document.images) {
info_savantgenius_com_over = newImage("images/info#savantgenius.com-over.gif");
About_over = newImage("images/About-over.gif");
Artist_over = newImage("images/Artist-over.gif");
Portfolio_over = newImage("images/Portfolio-over.gif");
Pricing_over = newImage("images/Pricing-over.gif");
Order_over = newImage("images/Order-over.gif");
Contact_over = newImage("images/Contact-over.gif");
About_over033 = newImage("images/About-over-33.gif");
Artist_over035 = newImage("images/Artist-over-35.gif");
Portfolio_over037 = newImage("images/Portfolio-over-37.gif");
Pricing_over039 = newImage("images/Pricing-over-39.gif");
Order_over041 = newImage("images/Order-over-41.gif");
Contact_over043 = newImage("images/Contact-over-43.gif");
preloadFlag = true;}
}
Within the body -
<td colspan="2">
<a href="mailto:info#savantgenius.com"
onmouseover="changeImages('info_savantgenius_com', 'images/info#savantgenius.com-over.gif'); return true;"
onmouseout="changeImages('info_savantgenius_com', 'images/info#savantgenius.com.gif'); return true;"
onmousedown="changeImages('info_savantgenius_com', 'images/info#savantgenius.com-over.gif'); return true;"
onmouseup="changeImages('info_savantgenius_com', 'images/info#savantgenius.com-over.gif'); return true;">
<img name="info_savantgenius_com" src="images/info#savantgenius.com.gif" width="220" height="49" border="0" alt=""></a></td>
You can simply use document.getElementById() instead of document[changeImages.arguments[i]]
function changeImages() {
if (document.images && (preloadFlag == true)) {
for (var i=0; i < arguments.length; i+=2) {
document.getElementById(arguments[i]).src = arguments[i+1];
}
}
}
You could use this :
http://api.jquery.com/hover/
So it would give you something like that :
$("#mytd1").hover(function(){$(this).css("background-image", [PUT THE NEW IMAGE PATH HERE])});
[PUT THE NEW IMAGE PATH HERE] something like that "url('image.jpg')"
And you need to include the jquery library

Categories

Resources