Javascript Random Clickthrough - javascript

I am creating an image which, when you click on it, sends you to one of four links. I have managed to code this, but the problem I am having is that it is completely random (only part of the point). What I would like to be able to do is to randomise the first click through, and then if the user goes back to the image, only leave them with the remaining three destinations, and then obviously two and one at the end. This is to stop them theoretically ending up at the same link every single time and not being able to access the other three.
Does anybody know how I might be able to do this? The code I have currently is:
<img src="IMAGE" onclick="randomLink();">
<script type="text/javascript">
var randomLink = function () {
var links = ["LINK 1","LINK 2","LINK 3","LINK 4",];
var max = (links.length)
var randomNumber = Math.floor(Math.random()*max);
var link = links[randomNumber];
window.location = "http://" + link;
}
</script>

You can simply remove the selected entry from the links array (i.e. using Array.splice). Next time the user clicks the link, you would generate a random number between 0 and 2 only and so on.

Related

How can the same button play different videos every time it's clicked?

I'm trying to hack together a video player to play local files in a cool interface, it's literally only ever going to be used by my family so the code doesn't have to be beautiful or anything. I've basically got a table full of DVD covers, and when clicked each one of them is supposed to open a modal with a video player for Chrome.
I've managed to do all of this, except I'm struggling to get it so the same button/image can be pressed and a different video file gets shown. Basically this is what I've got inside every table cell:
<th>
<div class="imageBox">
<div class="imageInn">
<img id="standardDVD" src="images/dvdCover1.jpg" alt="Snow">
<div class="hoverImg">
<img id="buttonPlay" src="images/play.png" alt="play">
</div>
</div>
</div>
</th>
I've then got the following JavaScript code to show the modal when that's clicked (I basically took it from here and modified it to show a video instead):
var playButton = document.getElementById('buttonPlay');
playButton.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
var dvdCover = document.getElementById('standardDVD');
dvdCover.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
(I've got two basically identical ones so it works if either the DVD cover or the button is clicked)
My thinking was to try and somehow get the src of the image (which should be doable if it's the image that's clicked, but I'm not too sure about how to get the dvd cover src if the button is the one getting clicked. From there I was thinking of having a simple (but long) JavaScript if function to convert each DVD cover to the src of the right video file, and simply change the videoToPlay variable used in the modal:
var videoToPlay = "movies/a Movie.mp4";
Edit since I don't think I was clear: I have a table with 55 different DVD covers, each in one cell and each with the identical HTML code except with a different dvdCover1.jpg image. What I'm trying to do is get it so each one plays the correct video, without having to make a new function for each.
I realize this is definitely not best practice, and any suggestions to improve the overall setup are appreciated - although I'm trying to get this together for Christmas and my knowledge of HTML and CSS is basically zero which is why I'm currently going for simplicity: only 5 people will ever see this anyway so best practice isn't necessarily important!
One option is to create an array with all your movies paths:
var videosToPlay = [
"movies/a Movie.mp4",
"movies/movie a.mp4",
"movies/a new Movie.mp4"
];
Then you need to get all handlers like this:
var dvdsCover = document.getElementsByClassName('standard-dvd-class-in-all-table');
Then just define the click event to all of them using the matching index. Your array must match the full table order of DVDs:
[...dvdsCover].forEach((dvdCover, index) => {
dvdCover.onclick = () => {
modal.style.display = "block";
document.getElementById("videoModal").src = videosToPlay[index];
};
});
Hope it helps.

Onclick event - MULTIPLE CLICKS

I'm building a site and I wish to have an image that once clicked it is replaced by another image and, on a second click, replaced by a third image an so on.
I've written a JavaScript function for this. The problem is that I can only call out one item on my index list, it never allows me several clicks to go trough all of my index items.
This is the code I've written so far:
function change (index) {
var links = new Array();
links[0] = img/videoplace.jpg;
links[1]="img/hiroshima.jpg";
var image = document.getElementById('social');
image.src = links[index];
}
<div class="box box1">
<img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)" >
</div>
Writing in the Html <img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)"> just causes the image to be replaced by the one corresponding to change(1) on first click.
Really appreciate any help that can be given.
Attach the event handler properly using Javascript instead (inline handlers are widely considered to be poor practice, and they're difficult to manage). Then, in the Javascript, you can keep a persistent variable of the current image index that's being displayed. On every click, increment the index, and display the appropriate image:
const links = [
'img/beehive.jpg', // first image is already displayed when page is loaded
'img/videoplace.jpg',
'img/hiroshima.jpg'
];
let index = 0;
const img = document.querySelector('#social');
img.addEventListener('click', () => {
index++;
img.src = links[index];
});
Note that declaring an array all at once is often nicer and more concise than using new Array() and assigning to indicies one-by-one.
If you want the displayed images to wrap around so that, once the last image is clicked on, the first image is displayed again, then use modulo. Instead of
index++;
do
index = (index + 1) % links.length;

javascript advance number onclick or on reload

I display a random DIV every time my webpage is reloaded using a simple function. This produces too many repeats because I only have seven divs.
<script type="text/javascript">
randomNumber = Math.floor(Math.random()*7+1);
window.onload = function() {
if (randomNumber == 1) {
document.getElementById("n1").style.display = "inline";
}
if (randomNumber == 2) {
document.getElementById("n2").style.display = "inline";
}
...[ETC. through 7]
}
}
</script>
I would like to solve this by replacing the "random number" with a predictable "progressing number". Can I advance a variable with every reload or onclick and execute the function to display each DIV in sequence? 1,2,3... displaying all seven divs before repeating.
I worry I would need cookies to do this with each individual visitor. Because the traffic is very low (likely one visitor at a time), perhaps I could use code from a page counter to achieve this.
I searched for any examples of this in action but found none. I would be very appreciative of any and all suggestions. Thanks for your time.
First of all, the random number you are generating, generates 3 everytime so no wonder you are getting all the repeats of third div.. change your random number generation code with this one:
var randomNumber = Math.floor(Math.random() * (7)) + 1;
This will generate a random number between 1 and 7 randomly. Then to display that particular div, instead of so many if or switch statements, you can simply do it in one line considering your div ids are n1, n2, n3 and so on..
document.getElementById("n"+randomNumber).style.display = "inline";
Put these two lines inside window.onload function so everytime window loads, a new random number gets generated and that div gets displayed.
This will work perfectly for many visitors as each visitor will get it's unique random number and that particular div will be displayed. No need to go into cookies or stuff like that.
See the Working snippet below, everytime you run it, a random div will be displayed:
var randomNumber = Math.floor(Math.random() * (7)) + 1;
document.getElementById("n"+randomNumber).style.display = "inline";
<div id="n1" style="display:none">DIV1</div>
<div id="n2" style="display:none">DIV2</div>
<div id="n3" style="display:none">DIV3</div>
<div id="n4" style="display:none">DIV4</div>
<div id="n5" style="display:none">DIV5</div>
<div id="n6" style="display:none">DIV6</div>
<div id="n7" style="display:none">DIV7</div>
EDIT: After understanding your question better (hopefully) and doing some research, i came up with a solution where you can retain the value of current div between page reloads, make a new html file on your computer, copy paste the following code and keep refreshing the page to see each div being displayed incrementally..
<!DOCTYPE HMTL>
<html>
<body>
<div id="n1" style="display:none">DIV1</div>
<div id="n2" style="display:none">DIV2</div>
<div id="n3" style="display:none">DIV3</div>
<div id="n4" style="display:none">DIV4</div>
<div id="n5" style="display:none">DIV5</div>
<div id="n6" style="display:none">DIV6</div>
<div id="n7" style="display:none">DIV7</div>
<script>
window.onload = function(){
if(window.name === "" || parseInt(window.name, 10) === 8) //this condition will be true when the page loads for the first time or the div values (window.name) exceeds 7 (Number of divs)
window.name = 1;
document.getElementById("n"+window.name).style.display = "inline";
window.name = parseInt(window.name,10) + 1; //incrementing the div number..
}
</script>
</body>
</html>
NOTE: Although the question has an accepted answer, I thought this was a closer to the question solution, so I posted it after reading the lines in the OP Can I advance a variable with every reload or onclick and execute the function to display each DIV in sequence? 1,2,3... displaying all seven divs before repeating. which meant that the OP author did not want to show them randomly through the divs.
You could use localStorage to make this happen. This will rotate through the 7 divs sequentially and display one at each page load and it's going to be user specific. That means, every user is assured to see all the divs sequentially.
if (typeof(Storage) != 'undefined') { // Check if localStorage is available in the browser
prevDiv = localStorage.getItem("myShowDiv"); // Fetch the previous that was shown to this browser
if (!isNaN(prevDiv)) prevDiv = parseInt(prevDiv); // If not first time
else prevDiv = parseInt('0'); // If it's first time
nowDiv = prevDiv + 1; // This div will be shown
if (nowDiv > 7) nowDiv = 1; // When all divs have been shown start from 1
localStorage.setItem("myShowDiv",nowDiv); // Save this div id for next page load
document.getElementById("div"+nowDiv).style.display = "inline"; // Show the div
}
Here's a fiddle

I need my JQuery slideshow to change div content on reload

Hello again my JS saviors! I have another dilema:: I have a div titled "homebanner" that contains text and a background image. My client decided that he wanted the #homebanner to change on reload with 4 images/slides.
So, I did this to change the background::
JS CODE
jQuery(function($){
$('#homebanner').css({backgroundColor: "#fff"});
var totalCount = 4;
var num = Math.ceil( Math.random() * totalCount );
function setBGImage() {
var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
$('#homebanner').css(
{
backgroundImage:"url("+bgimage+")",
});
}
setBGImage();
});
And it works great! So I'm stoked about that. But I can't figure out a way to have specific headline text to correspond with each image. Is this possible? Also, here's a link to the test site http://www.bwpcommunications.com/TESTING/. As you can see, when you refresh the page the image changes but the text does not.
Any help would be awesome!
Thanks,
Shadna
put whatever headline text options you want into an array
var hText = ["blue jeans", "red jeans", "ripped jeans", "plaid"];
then right after setting the background image, you can use the num variable to pick the corresponding text from the array (or if you want it random you can just do the random number generation again). Then it's just a matter of setting the text on the page.
$('#htxt').html(hText[num]);
or in plain javascript:
document.getElementById('htxt').innerHTML = hText[num];
depending how the images are numbered, you might need to do num - 1 since the array is 0 indexed.

Javascript - changing image won't work unless i alert()

I'm building a JavaScript based poker game that get some updates from a server via Ajax.
when player are in "show down" each one of them supposed to show what card he holds,
I'm changing the pictures of each showdown hand (from blank card to an actual card i.e King of spades img)
I have the weirdest problem: when i change the images (as shown in the code below),
the images wont change from blanks to actual cards, they remain "blank.png".
whats weird is if i remove the "//" from line9 (and get an alert message) the cards are shown with their actual image i.e "Ace of spades.png"..
what's with that?!
function executeShowDown(){
(...)
var playerCard1Id = "#player"+(playerNum)+"card1"; //the specific image id for hole card #1
var playerCard2Id = "#player"+(playerNum)+"card2"; //the specific image id for hole card #2
var card1 = "res/images/cards/"+handArr[0]+".png";
var card2 = "res/images/cards/"+handArr[1]+".png";
$(playerCard1Id).attr("src", card1);
$(playerCard2Id).attr("src", card2);
$(playerCard1Id).css('visibility','visible');
$(playerCard2Id).css('visibility','visible');
//alert("endShowDown"); ##### LINE 9 #####
return;
}
This might be happening too fast. Maybe add something to make it wait for 1 second or so, or you could use a callback function, I see you use return there so maybe the other function where you call this from does not wait for it to end.
Good luck!

Categories