Random image click - javascript

So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.
function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}
Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?

You can try to select the image who have the wanted source.
And add a class or id to your paragraph for readability.
document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};
Example
document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
document.getElementById("rep").innerHTML="you win !";
}
img{
height:100px;
width:100px;
}
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">

<script type="text/javascript" >
var images = document.getElementsByTagName('img');
//find all paragraphs
var paragraphs = document.getElementsByTagName('p');
//define function called on click
function changeParagraph() {
//change first paragraph if exists
if(paragraphs.length) {
paragraphs[0].innerHTML = 'I have been changed!';
}
}
/*
for(var i = 0; i < images.length; i++) {
//set onclick event to every image
images[i].onclick = changeParagraph;
}
*/
// set onclick to the randomImage
images[randomNumber].onclick = changeParagraph;
</script>

Assuming your first paragraph exists before the user clicks the picture, you can add an onClick element to your img tag. Try something like this, changing the URL obviously for your own picture:
<p id = "first">You haven't found Waldo
</p>
<img id = "waldo" src = https://pbs.twimg.com/profile_images/561277979855056896/4yRcS2Zo.png
onclick = "addparagraph()"
/>
JavaScript:
function addparagraph(){
document.getElementById("first").innerHTML = "you found Waldo!";
}

Related

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.
v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\"
onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";
That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.
Thoughts?
I just grabbed some images off google images. You can use this to refer to the current element.
<img
src='https://osu.ppy.sh/forum/images/smilies/50.gif'
onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"'
onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"'
/>
Edit..
This will change the image when you hover on anything with a "hoverme" class name.
(function() {
var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif";
var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png";
var myimg = document.getElementById('myimg');
myimg.src = img1;
var hoverables = document.getElementsByClassName('hoverme');
for (var i = hoverables.length; i--;) {
hoverables[i].addEventListener("mouseover", hoverMe, false);
hoverables[i].addEventListener("mouseout", unhoverMe, false);
}
function hoverMe() {
myimg.src = img2;
}
function unhoverMe() {
myimg.src = img1;
}
})();
<img class='hoverme' id='myimg' />
<p class='hoverme'>poooooooop</p>
<div class='hoverme'>This si a diiiiivvvvv</div>
The best way to accomplish that is to use CSS.
HTML
<img id="NavIcon">
CSS
#Navicon {
background-image: url(image1.jpg);
}
#NavIcon:hover {
background-image: url(image2.jpg);
}

Multiple Id's calling on same JavaScript function

I am trying out a JavaScript where it takes Id of an image and onclick of the image it performs some function. But I have multiple Id's of same image where the id of the onclick'ed image should be processed by JavaScript and the operation should be performed.
Problem is I am not able to get the right id based on the click.
here is my code
1)myhtml
<div class="col-md-3 col-sm-6">
<div class="sub-process-block quantity">
<h3>choose quantity</h3>
<div id="example" onclick="changeImage()">
<img src="img/carton-empty.png" id="myImage">
<img src="img/carton-empty.png" id="myImage1">
<img src="img/carton-empty.png" id="myImage2">
</div>
</div>
2)javascript
<script>
function changeImage() {
var imageArray=["myImage","myImage1","myImage2"];
for(var i=0;i<imageArray.length;i++ ){
image = document.getElementById(imageArray[i]).onclick;
}
if(image.src.match("selected")) {
image.src="img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
Why don't you add an event listener to your images in JS? Then you can check if it's selected or not and update the source accordingly
// get all images and put them in an array
var images = [].slice.call(document.querySelectorAll('img'));
// loop through images and add event listener
images.forEach(function(image) {
image.addEventListener('click', onImageClick);
});
// on click, check if image is selected and update src
function onImageClick(e) {
var image = e.target;
if (image.src.match("selected")) {
// is selected, now unselected it and update src
image.setAttribute('src', 'img/carton-empty.png');
} else {
// is not selected, now select it and update src
image.setAttribute('src', 'img/carton selected.png');
}
}
https://jsfiddle.net/0qzdsf8r/4/
Inspect the image elements in the dev tools and see the class and src change.
Try this ;)
function changeImage(){
var imageArray = ["myImage", "myImage1", "myImage2"];
for(var i = 0; i < imageArray.length; i++){
var image = document.getElementById(imageArray[i]);
if(image.src.match("selected")){
image.src = "img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
}
You placed condition outside for loop;

Automatic slideshow with PHP and JavaScript

So basically i have made a PHP program that takes pictures from a folder and puts it into the "slideshow" in Gallery. The PHP code gives the images id's starting from "1" and so on.
Now with JavaScript i want it to automatically switch picture every 2,5 second. It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help.
Any help would be appreciated.
<div id="gallery" class="grey">
<h3>Gallery</h3>
<div id="slideshow">
<?php
$path = "./img/gallery";
$all_files = scandir($path);
$how_many = count($all_files);
for ($i=2; $i<$how_many;$i++) {
$kubi=$i - 1;
echo "<img src=\"./img/gallery/$all_files[$i]\" id= \"$kubi\"/>";
}
?>
</div>
</div>
JavaScript code:
var picture = document.getElementById("1");
var i = 0;
function rotateImages() {
while (i < document.getElementById("slideshow").childNodes.length) {
picture.style.display = "none";
picture = picture.nextSibling;
picture.style.display = "inline";
i++;
};
};
window.onload = function(){
document.getElementById("1").style.display = "inline";
setInterval(rotateImages(), 2500);
};
What happens is that always uses the same first element picture, hides it and then shows the second image, it does not actually iterate through all the pictures.
In your code, picture always is the first element, next is always the second.
Also, it should not be a while loop since the callback is called once to change a picture, so change it to if, and reset to the first picture when it passes number of total elements.
It should be: (Javascript)
var firstPicture = document.getElementById("1");
var picture = firstPicture ;
var i = 0;
function rotateImages() {
// hide current element
picture.style.display = "none";
// choose who is the next element
if (i >= document.getElementById("slideshow").childNodes.length) {
i = 0;
picture = firstPicture;
} else {
picture = picture.nextSibling;
}
// show the next element
picture.style.display = "inline";
i++;
};
window.onload = function(){
var curImg = document.getElementById("1").style.display = "inline";
setInterval(rotateImages, 2500);
};

adding a click event to confirm image color javascript

I was writing a javascript game so that everytime 4 different random colors are placed on the screen as images and the player is asked to click on the green color, however I cant find what to write on the click function even after searching so much, also how to I make the images keep changing automatically every few say for example 2 seconds
heres how the game works :
when the page loads, 4 blank white images are shown
after clicking on the start button 4 different colors take place of the blank image
after clicking on the green image the game should say alert something
I used 0-5 code for colors on the script for img src 0.jpg being for white , 1-4 green red blue brown respectively
any help would be appreciated
the code : http://jsfiddle.net/gf2un/1/
JS
var counter = 0;
var greenNumber;
function start() {
var button = document.getElementById("startButton");
button.addEventListener("click", generateColor, false);
}
function generateColor() {
var color;
var imgCheck = [];
for (var i = 1; i <= 4; ++i) {
do
color = Math.ceil(Math.random() * 4);
while (imgCheck.indexOf(color) !== -1)
if (color == 1) greenNumber = i;
imgCheck[i] = color;
setImage(i, color);
}
}
function setImage(rdmNumber, color) {
var rdmImg = document.getElementById("color" + rdmNumber);
rdmImg.setAttribute("src", "images//" + color + ".jpg");
rdmImg.setAttribute("width", "90px");
}
function Click( clickedImage )
{
var theSrc = clickedImage.src;
if (theSrc = "image/1.jpg")
++counter;
document.getElementById('score').innerHTML = "Score : " + counter;
}
window.addEventListener("load", start, false);
HTML
<center>
<p>CLICK ON THE GREEN SQUARE</p>
<p>
<img id = "color4" src = "images/0.jpg" alt = "box 1 image" width = "90px" onClick = "Click(this)">
<img id = "color1" src = "images/0.jpg" alt = "box 2 image" width = "90px" onClick = "Click(this)">
</p>
<p>
<img id = "color2" src = "images/0.jpg" alt = "box 3 image" width = "90px" onClick = "Click(this)">
<img id = "color3" src = "images/0.jpg" alt = "box 4 image" width = "90px" onClick = "Click(this)">
</p>
<form action = "#">
<input id = "startButton" type = "button" value = "Start">
</form>
</center>
</body>
You are doing it too complex; you don't need to create REAL images. Instead, play with the css a little. It makes the code look more neat, and the player doesn't require to download the images.
Shuffling is easy, when you are using a container.
Add click functions with method addEventListener(). This adds an event to the HTML object, so you can add more than one function to it.
Here's my working version of your game: http://jsfiddle.net/kychan/k3J9b/1/ Try it! No seriously, i made this game for you! Inspect it, copy it or use it fully, it's all yours! I also added lots of comments for you.
Shuffle example:
// changes the color and shuffles the deck.
function newColor() {
// we change the color we want the user to press.
var rand_color = randomValue(colors);
curColor.innerHTML = rand_color;
// we also change the color of the span, so it changes the text color.
curColor.style.color = rand_color;
// we shuffle constant SHUFFLE_MAX times and re-add it to the container.
for (var i=0; i<SHUFFLE_MAX; i++) {
container.appendChild( randomValue(boxes) );
}
}
returns a random value in the array:
function randomValue(array) {
return array[(Math.floor(Math.random()*array.length))];
}

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

Categories