How to add website links to a random image generator - javascript

i have this code and want to know how to add website links to the images, once the random image is generated i want the image can be clicked to go to a predetermined list of websites, it's a really beginner question since i don't really understand javascript functions.
Thank you.
<html>
<head>
<script type="text/javascript">
//preload the six images first
var face0=new Image()
face0.src="d1.gif"
var face1=new Image()
face1.src="d2.gif"
var face2=new Image()
face2.src="d3.gif"
var face3=new Image()
face3.src="d4.gif"
var face4=new Image()
face4.src="d5.gif"
var face5=new Image()
face5.src="d6.gif"
</script>
</head>
<body>
<img src="d1.gif" name="mydice">
<form>
<input type="button" value="Throw dice!" onClick="throwdice()">
</form>
<script>
function throwdice(){
//create a random integer between 0 and 5
var randomdice=Math.round(Math.random()*5)
document.images["mydice"].src=eval("face"+randomdice+".src")
}
</script>
</body>
</html>

You don't need to use the (dangerous) eval() function nor do you need to pre-load the images for this.
Just place all your image links (d1.gif, d2.gif, etc) in an array and similarly, place all the links you want the images to respectively link to in another array.
In your HTML, wrap the <img> element in an anchor tag <a> and now you can just update the anchor tag's href value as well as the img src value whenever the button is clicked.
Also, you don't need a form for the button. Just create the button as a separate element and add the click event listener to that button.
Check and run the following Code Snippet for a practical example of the above approach:
//get the anchor tag that has the image and the button
const image = document.querySelector('a');
const btn = document.querySelector('#btn');
//assign the src links and href links to arrays
const links = ["someLink1", "someLink2","someLink3","someLink4","someLink5","someLink6"]
const images = ["d1.gif","d2.gif","d3.gif","d4.gif","d5.gif","d6.gif"]
//update the src link and href link
function throwdice(){
const randomIndex = Math.round(Math.random()*5);
image.href= links[randomIndex];
image.firstChild.src= images[randomIndex];
}
//run the function when the button is clicked
btn.addEventListener('click', throwdice)
<h3>Right-click the image and inspect it to see the anchor tag link and the img src link change whenever the button is clicked</h3>
<img src="d1.gif" name="mydice">
<button id="btn">Throw dice!</button>

Here is how you can make it with JavaScript
function getRandom(){
var RandomNumber1 = Math.floor(Math.random() * 6) + 1;
var link =["Link1","Link2","Link3","Link4","Link5","Link6"]
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = '<img src="dice' + RandomNumber1 + '.png">';
}
<input type="button" value="Throw Dices" onClick="getRandom()">
<div id="result">
<img src="d1.gif" name="mydice">
</div>

Related

What is the function to add a link to a graphic in javascript under document.createElement?

I am setting up a timeline using examples from http://visjs.org/docs/timeline/#Example. Can someone tell me what I need to add a local link to the graphic I have?
I have tried a.href, but maybe I am doing something wrong. Here is a snippet with my code commented out:
var item5 = document.createElement('div');
item5.appendChild(document.createTextNode('item 5'));
item5.appendChild(document.createElement('br'));
var img5 = document.createElement('img');
// img5.a.href = 'attachments/AddDuties.pdf';
img5.src = 'icons/pdf1.png';
img5.style.width = '48px';
img5.style.height = '48px';
item5.appendChild(img5);
Here is the some more code (I cut parts out to reduce size, it works before I add my own code below on image 5:). Image 5 is the one I want link the graphic to a file.
<title>Timeline | Basic demo</title>
<script src="vis-4.21.0/dist/vis.js"></script>
<link href="vis-4.21.0/dist/vis.css" rel="stylesheet" type="text/css" />
</head>
<body>'
<script>
// create a couple of HTML items in various ways
var item1 = document.createElement('div');
item1.appendChild(document.createTextNode('item 1'));
var item4 = 'item <span class="large">4</span>';
**var item5 = document.createElement('div');
item5.appendChild(document.createTextNode('item 5'));
item5.appendChild(document.createElement('br'));
var img5 = document.createElement('img');
// img5.a.href = 'attachments/AddDuties.pdf';
img5.src = 'icons/pdf1.png';
img5.style.width = '48px';
img5.style.height = '48px';
item5.appendChild(img5);**
</body>
I expect to be able to click the graphic and follow the assigned link. I know how to use href in HTML, I just dont know what code needs to tell javascript how to link the graphic in image 5.
href is an attribute for the <a> tag. you can't add href to an image.
What you should do is create an <a> element assign the href you want to it and
append the img as a child of that <a> element.
<a href="{whatever you want}">
<img src=....>
</a>
edit:
if for some reason you can't wrap the image with an <a> you could assign and id to the image and then add an event listener for a click that will redirect you.

Replace img src with js jquery

I have a newsfeed in my CMS that pulls preview images as well as teaser text for the feed. The images are all thumbnails # 75x75px. I wanted to have the preview images much larger, but cannot scale an image that small.
I'm wondering what JS I need to run to replace all the URL's to the original image src.
Have:
Need to change them all to the below - which is just replacing 'thumb' with 'large':
This needs to apply to a whole css class; as it is a newsfeed & there will be new articles
Here's where I'm at:
function replaceImgSrc(img,imgTwo) {
var arr=[img,imgTwo];
for(i=0;i<arr.length;i++)
arr[i].each(
function(i,e) {
theImg=$(this),
theImg.attr("src",
function(i,e) {
return e.replace("_thumb","_large")
}
)
}
)
}
If the newsfeed is wrapped in a class, try this way.
function replaceImg($class) {
$class.find("img").each(function(k, el) {
var newSrc = $(el).attr("src").replace("_thumb", "_large");
$(el).attr("src", newSrc);
});
}
replaceImg($("#newsfeed"));
And in your HTML, wrap the newsfeed code inside an identifiable DIV.
<div id="newsfeed"> {{place newsfeed code in here}} </div>
Try this fiddle jsfiddle.net/bharatsing/wkh6da93/
This will find all images in page and change its src with large image.
$(document).ready(function(){
$("#btnLarge").click(function(){
$("img").each(function(){
var src=$(this).attr("src");
src=src.replace("_thumb","_large");
var src=$(this).attr("src",src);
});
});
});
If the assumption is that you have all img elements in an array var imgArray, then you can iterate thru them and update the src attribute like this:
imgArray.forEach(enlargeImageSrc);
function enlargeImageSrc (image) {
image.src = image.src.replace('_thumb', '_large');
}
Try this hovering over the button will make the images with class="show" bigger, as soon as you remove the mouse they are small again.
$("button").mouseenter(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("thumb","large");
$(".show").attr("src",srcI);
});
$("button").mouseleave(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("large","thumb");
$(".show").attr("src",srcI);
});
button{
display:block;
}
img.show{
max-width:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button>Click me</button>
<img class="show" src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png"/>
</div>
I make a code for you where I take two variables one for large image URL and one for small image URL. I create a function on click on change image button your image url change to big image and it show you big image and then you again click on that button it change big image to small image. You can also see the live demo of this here https://jsfiddle.net/Arsh_kalsi01/3s1uudhe/2/
$(document).ready(function(){
var big_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_large.png";
var small_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png";
$(document).on("click",".Changeimagetolarge",function(){
var obj = $(this);
obj.removeClass('Changeimagetolarge');
obj.addClass('Changeimagetosmall');
obj.next("img").attr('src',big_image);
});
$(document).on("click",".Changeimagetosmall",function(){
var obj2 = $(this);
obj2.removeClass('Changeimagetosmall');
obj2.addClass('Changeimagetolarge');
obj2.next("img").attr('src',small_image);
});
});
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<div>
<button class="Changeimagetolarge">
Change Image
</button>
<img src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png">
</div>

Change image within div on image icon click

I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>

Add letters to image source through javascript

In my photo gallery I have it so on click of an image it just changes the larger image to the source of it. But now I want the onclick function of the image to take the source that it would originally inject into the image and add 3 letters to the end before injecting, "lrg".
Javascript:
<script type="text/javascript">
function setImg(a){
document.getElementById('ImageFrame').src =
a.getElementsByTagName('img')[0].src
}
</script>
Html image that you click.
<a href="#gallery" onclick="setImg(this);"><img class="gallery" src="JCF/PICT0421.jpg"
/></a>
Larger image that changes:
<div>
<img id="ImageFrame" src="JCF/PICT0422.jpg" width="500" />
</div>
When the link injects into the "imageframe" I want the source to change to JCF/PICT0421lrg.jpg
If i got it right, this will solve our problem.
<script type="text/javascript">
function setImg(a){
var arr = a.getElementsByTagName('img')[0].src.split(".");
document.getElementById('ImageFrame').src = arr[0]+"lrg"+"."+arr[1];
}
</script>
extended example
http://jsfiddle.net/ymutlu/E9Fq5/
In change setImg to
function setImg(a){
var file_parts = a.getElementsByTagName('img')[0].src.split(".");
var new_name = file_parts[0] + "lrg." + file_parts.slice(1).join(".");
document.getElementById('ImageFrame').src = new_name;
}
This will add the "lrg" before the first dot in the filename.

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};​
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>

Categories