Image rotater in javascript only - no jquery - javascript

UPDATE: The answer below seemed to work, but if I have links in my text in the descriptions variable, it doesn't seem to replace the text at all. If i remove tags, or any html tags from all the text I am trying to replace, it works. Issue is, I need the text to be replaced to be html format :(
I am trying to get an image to fade, with text outside of the image to fade as well, and have another set appear in same place.
jquery can not be used due to the environment.
I came up with this, the only issue is that the very first thing that happens is the first image fades at the very start and the same image appears. Then it starts working normal after that first "glitch". After that, if seems to work perfectly.
Can someone point out my silly mistake?
<script type="text/javascript">
var links = ["http://www.firstlink.com","http://www.secondlink.com","http://www.thirdlink.com"];
var images = ["1stimage.jpg","2ndimage.jpg","3rdimage.jpg"];
var descriptions=["this is the first set of rotating text", "Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text."]
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
fadeIn(document.getElementById("bannerImage"), 1000);
document.getElementById("bannerLink").href = links[i];
document.getElementById("p1").innerHTML= descriptions[i];
i++;
}
},5000);
</script><script type="text/javascript">
function fadeIn(el, time) {
el.style.opacity = 0;
el.style.display = "block";
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
</script><img alt="some text" height="83" id="bannerImage" src="1stimage.jpg" width="633" />
<p id="p1">this is the first set of rotating text</p>

Change this
var images = ["1stimage.jpg","2ndimage.jpg","3rdimage.jpg"];
var descriptions=["this is the first set of rotating text", "Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text."]
to this
var images = ["2ndimage.jpg","3rdimage.jpg","1stimage.jpg"];
var descriptions=["Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text.", "this is the first set of rotating text"]

Related

javascript value is not updating after onmousevent

I use 1 span tag at the moment.
<span onmouseover="numberOne()" onclick="imgNumber(); return false" onmouseout="noHoverOne()" class="img1 img" id="new-img"> </span>
The span has a "deafult" image, when the mouse goes on the span, another image will be shown, when the mouse leaves the span, the default image will be shown again.
now the javascript:
function numberOne() {
var random2 = Math.floor((Math.random() * 3) + 1);
var random3 = Math.floor((Math.random() * 3) + 1);
do {
var random = Math.floor((Math.random() * 3) + 1);
} while (random === numberOne.last);
numberOne.last = random;
Random numbers are made here. So every time you leave the span and go on the span, there will be a different image.
if (random == 2) {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/molgeld.jpg');";
} else if ((random==random2)==random3) {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/vrijstelling.jpg');";
} else {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/haspel.jpg');";
}
These are the images that will be shown depending on the number
return random;
}
var value = numberOne();
function imgNumber() {
document.getElementById('demo').innerHTML = value;
}
imgNumber();
This is where I am stuck. Before I even have touched the span tag with my mouse, there is already a random number and when I go with the mouse on the span tag, it shows a different image but not a different number. I want to use this number somehow to create a new level for my game. The game is influenced by the chosen image.
So there is a lot going on and it's pretty messy. So please, I would love to hear any kind of constructive feedback.
[EDIT] I will keep the JSfiddle up to date, but there is an error in the preview, it won't display anything. It's still useful Jsfiddle
use a wrapper function where you can call both imgNumber and numberOne
function mouseHover() {
var value = numberOne()
imgNumber(value)
}
function imgNumber(value) {
document.getElementById('demo').innerHTML = value;
}
<span onmouseover="mouseHover()" onclick="imgNumber(); return false" onmouseout="noHoverOne()" class="img1 img" id="new-img"> </span>
Your code is a bit illogical. It seems you want to randomly assign an image to an element background and get a different element each time. So put the image URLs in an array and randomly grab one, ensuring it's different to the last. This means you can add or reduce the images you want to display just by modifying the images array.
Also put all your data in an object rather than using globals, it's just neater. And give your functions names that tell you what they do.
E.g.
var imageData = {
pix: ['http://web-stars.nl/molgeld.jpg',
'http://web-stars.nl/vrijstelling.jpg',
'http://web-stars.nl/haspel.jpg'
],
random: null
}
function changeImage(el) {
// limit do loop just in case data is bad
// Infinite loops are bad...
var len = imageData.pix.length;
var i = len;
do {
var random = Math.random() * len | 0;
} while (i-- && imageData.random == random)
imageData.random = random;
el.style.backgroundImage = imageData.pix[random];
console.log(random, imageData.pix[random]);
}
function updateImageRef() {
document.getElementById('imageRef').textContent = imageData.random;
}
<div id="imageDiv" onmouseover="changeImage(this)" onclick="updateImageRef()">Image div</div>
<div id="imageRef"><div>

How to get dialogue to change upon clicking on an image?

I'm trying to create a game with dialogue, and I want my text to change as the player clicks on a next image to progress the story.
For example:
Page loads - "Hi, I'm Joe."
Clicks sliced Image once - "Nice to meet you."
Clicks 2nd time - "How are you?"
I have tried onClick but that only allows me to change it once, I've tried using var counter as well but to no avail, it overrides my previous commands, which part of this am I doing wrong here?
var clicks = 0;
function changeText() {
{
clicks = 1;
document.getElementById('text').innerHTML = "Ughh... my head... What
happened...?";
}
}
function changeText() {
{
clicks = 2;
document.getElementById('text').innerHTML = "Testing 1 2 3";
}
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText(); audio.play()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>
First off all - your changeText() system is flawed - you're overwriting the same function multiple times at the same time, so the only one of those that will ever get called is the last one you declare. JavaScript doesn't wait until a function gets called to continue with the program.
The audio.play() also won't work - but I'm assuming that's a work in progress.
I changed your code so that instead of setting count to a specific value, it increments every time the function gets called, and it updates the text to the correct value in an array. Here's the updated changeText function:
var count = 0;
var text = [
"Where... am I...?", /* note that this will never get called, it's simply here for filling up the array*/
"This is the first text!",
"And this is the second!"
]
var changeText = function() {
count++;
document.getElementById('text').innerHTML = text[count];
}
In the future, you'll probably also want to check if(text[count] != 'undefined'), and if so write something like "Bye!" instead.
Issues in your code
Multiple function declaration of changeText()
Extra {} in changeText()
You are not updating value of clicks.
In your html, you have written audo.play() but no audio object is available. It should be play(). I have called play() function in changeText() function. This keeps HTML clean.
Following is updated code:
var clicks = 0;
function changeText() {
var text = ""
clicks++;
switch(clicks){
case 1: text = "Ughh... my head... What happened...?";
break;
case 2: text = "Testing 1 2 3";
break;
}
document.getElementById('text').innerHTML = text;
play();
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>

Delay Display of Text in Qualtrics using Javascript

(This is related to the unanswered question https://stackoverflow.com/questions/26745762/delaying-presentation-of-text-in-qualtrics)
I am working on a Qualtrics survey. I want to delay some text (say, text) being displayed - it should be hidden for 5 seconds, then display.
I found a resource here - Javascript for Qualtrics - that I can't get to work.
Drawing from this example, I try to replicate it by delaying the display of a photo. I do this to see if I can get this working before I go on to delaying the display of text as opposed to a photo.
In the HTML part, I put:
Time: <span id="time1">30</span><br>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/%C3%81guila_calva.jpg/1280px-%C3%81guila_calva.jpg" style="width: 133px; height: 115px;" class='pic1' />
In the Javascript part, I have:
started = false;
function countDown1() {
if (!started)
started = true;
else {
var value1 = parseInt($('time1').innerHTML);
$('time1').innerHTML = value1 - 1;
if (value1 == 26) {
var styling1 = document.getElementsByClassName('pic1')[0];
styling1.style.display = "none";
}
}
setTimeout(countDown1, 1000);
}
Event.observe(window, 'load', countDown1);
For some reason, nothing happens at all with the timer or the photo.
Do I need to wrap the above Javascript in:
Qualtrics.SurveyEngine.addOnload(function()
{
});
I tried this as well, but no change.
So I really have two questions. 1. How do I modify the above code to get it working. And 2. How do I modify the working version of the code to display text after a certain amount of time?
You're making it more complex than need be.
Here is example html for the question:
This is a question. <span id="hiddentext" style="display:none">This text
will display after five seconds.</span>
Here is the javascript for the question:
Qualtrics.SurveyEngine.addOnload(function()
{
setTimeout("$('hiddentext').style.display = 'inline'",5000);
});
This hides the radiobuttons or Choices in a multiple choice question for 2 seconds. If you need to hide the next button as well you can add a Timing question from the ones already provided in Qualtrics and set it to "Enable submit after (seconds)".
Qualtrics.SurveyEngine.addOnload(function() {
var QID = this.questionId;
console.log(QID);
for (var i = 1; i < 4; i++) {
document.getElementById( QID + "-" + i + "-label" ).style.display="none";
}
(function(delay_container){
for (var i = 1 ; i < 4 ; i ++){
document.getElementById(QID + "-" + i + "-label").style.display="block";
}
}).delay(2,this.questionContainer);
});
Let's say you have two sentences that are two separate Descriptive text boxes. And you want the second box to appear some seconds after the first. The following worked for me when assigned for the second box. The same code works for following boxes as well. You can again put a Timing question at the end of the page to hide Next button.
Qualtrics.SurveyEngine.addOnload(function() {
var QID = this.questionId;
console.log(QID);
for (var i = 1; i < 4; i++) {
document.getElementById( QID).style.display="none";
}
(function(delay_container){
for (var i = 1 ; i < 4 ; i ++){
document.getElementById(QID).style.display="block";
}
}).delay(2,this.questionContainer);
});

Show / Hide images randomly using jQuery

I want to create a function that grabs all the instances of an image class on the page. As default these will be hidden, then randomly after a certain interval show one of those images (can be any image). Then the function will rerun and show another image. (whilst hiding the image that was shown on the first run through.
I've got to this stage with the function (not currently working)
(function randomShow() {
var showDiv = $('.show'),
el = showDiv.eq(Math.floor(Math.random() * showDiv.length));
el.show().delay(2000).show(randomShow);
})();
Thanks
I put together a jsFiddle using divs in place of images to demonstrate (pure js):
http://jsfiddle.net/oogley_boogley/az9gd8wf/
the script:
var divs = document.getElementsByClassName('square');
var arrLength = divs.length;
var randomNumberLimit;
var interval_speed = 1000;
setInterval(function(){
randomNumberLimit = Math.floor((Math.random() * arrLength) + 1);
for(i=0;i<arrLength;i++){
var matchingDiv = divs[i];
if(matchingDiv.id == randomNumberLimit){
matchingDiv.setAttribute("class","showing square blue");
}
if(matchingDiv.id != randomNumberLimit){
matchingDiv.setAttribute("class","hiding square blue");
}
}
}, interval_speed);

Showing random divs images every time page is load

Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?
http://creativepreviews.com/fiddle/study/20131007/
Let's say the image will display in the background of the DIV, then the following should do it.
// JS
var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]
function randomBg() {
x = Math.random()
y = Math.round(x * 10)
if (imgArray[y] != undefined) {
document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
} else {
document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
}
}
...and the HTML.
<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>
...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...
You could do something along these lines (not tested)
var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);
In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.
If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.

Categories

Resources