Image Changing in HTML and Jquery - javascript

I am working on a personal coin flip project in HTML and Javascript. Is there a way to make the an image change based on the result of the "flip". For instance if it lands on heads it shows an image of a quarter on its heads side and same for tails?
Javascript Code:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML Code:
<button id="click" type="button">CLICK ME</button>
<p>You got: <span id="result"></span></p>

You have the working code you just need this...
var coins = {
heads: 'http://lorempixel.com/400/200/sports/heads is sports',
tails: 'http://lorempixel.com/400/200/animals/tails is animals',
}
document.getElementById("result").setAttribute('src', coins[coin])
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
var coins = {
heads: 'http://lorempixel.com/400/200/sports/heads is sports',
tails: 'http://lorempixel.com/400/200/animals/tails is animals',
}
function click() {
var result = Math.floor(Math.random() * 2) == 0 ? 'heads' : 'tails';
flip(result)
};
function flip(coin) {
document.getElementById("result").setAttribute('src', coins[coin])
};
<button id="click" type="button">CLICK ME</button>
<p>You got: <img id="result" /></p>

Simply change the .src on an <img />:
(The link can be anything you want, including a relative path, for example: "../../img/")
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("head");
}else{
flip("tail");
}
};
function flip(coin) {
var link = "http://www.marshu.com/articles/images-website/articles/presidents-on-coins/half-dollar-coin-";
document.getElementById("result").src = link+coin+".jpg";
};
img {width:100px;}
<button id="click" type="button">CLICK ME</button>
<p>You got: <img id="result" src="" /></p>

Related

Z-index in script [duplicate]

I made a website which consists of a display area that randomly spawns 50 circular <div> elements. I want to make it so when one of the circles is clicked, it comes to the foreground. I thought using the addEventListener function on each circle as it's created would work but I can't get it to do anything. Thank you.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="index_styling.css">
<script type="text/javascript" src="index_scripts.js"></script>
</head>
<header>
<h1>First Last, Assignment #6</h1>
</header>
<div id="orange_strip"></div>
<body>
<form>
<ul>
<li>
<input type="button" name="add" value="Add Square">
<input type="button" name="change" value="Change All Square Colors">
<input type="button" name="reset" value="Reset All Squares">
</li>
</ul>
<div id="display">
</div>
</form>
</body>
<footer>
<div id="copyright">Copyright &copy 2016 - First Mid Last</div>
</footer>
</html>
JavaScript
window.onload = function() {
for (var i = 0; i < 50; i++) {
var display_div = document.getElementById("display");
var circle = document.createElement("div");
var randNum = getRandomDimension(5000);
circle.setAttribute("class", "circle");
circle.style.backgroundColor = getRandomColor();
circle.style.position = "absolute";
circle.style.left = getRandomDimension(550);
circle.style.top = getRandomDimension(450);
circle.addEventListener("click", bringToFront(circle));
display.appendChild(circle);
}
}
function bringToFront(element) {
element.style.zIndex = "1";
}
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function getRandomDimension(max) {
var num = Math.floor((Math.random() * max) + 1);
var str = num.toString();
return str += "px";
}
This line:
circle.addEventListener("click", bringToFront(circle));
...does not add an event listener. It calls your bringToFront() method immediately and then attempts to assign its return value as a listener except the return value is undefined. (Meanwhile, the effect of calling that function immediately within the loop means all of your divs get set to z-index: 1 upon their creation.)
You should be passing a reference to the function (note there is no () after the function name):
circle.addEventListener("click", bringToFront);
...and then change the function to work with this, because this will automatically be set to the clicked element at the time the function is called for the event:
function bringToFront() {
this.style.zIndex = "1";
}
The problem is with the current line
circle.addEventListener("click", bringToFront(circle));
That is trying to execute the bringToFront function right away.
AddEventListener just needs to function, and it will execute it when the event fires
circle.addEventListener("click", bringToFront);

It doesn't move to the next image

I am trying to create a slideshow. I have created two buttons because I want to do it in two ways. One way is when I press the next button to move to the next image(single image movement) and when I press the slideshow button to make it move along with not pressing a button. I didn't manage to fix it. Please help me if you can.
var img = new Array();
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
if (i < img.length - 1)
i++;
else
i = 0;
document.getElementById("img1").src = img[i];
}
startslideshow() {
id = window.setInterval("Next()", 1000);
var x = document.getElementById("txt").value;
id2 = window.clearTimeout("Cancel()", x * 1000)
}
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
</body>
here is the solution that we have came up with
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
<button onclick="stopslideshow()">stopSlideShow</button>
</body>
var img = new Array();
var cur = 0;
var timer = null;
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
cur = (cur < img.length - 1) ? cur + 1 : 0;
document.getElementById("img1").src = img[cur];
}
function startslideshow() {
timer = setInterval(function() {
Next();
}, 500);
}
function stopslideshow() {
if (timer) {
clearInterval(timer);
timer = null;
}
}

use location.hash to keep page status in javascript

I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

animate elements in random sequence

I try to animate some buttons. A random string should be generated that the animated buttons arent always in the same sequence. fiddle
an example:
text = 1423
the first animated button is btn1 then after one second btn4 then after one second btn2 then after one second btn3
the buttons:
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="" class="button"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="" class="button"></button>
</div>
<div>
<button name="btn3" type="submit" id="btn3" value="3" style="" class="button"></button>
<button name="btn4" type="submit" id="btn4" value="4" style="" class="button"></button>
</div>
the javascript:
var textArray = [];
var text = "";
function makeid()
{
var possible = "1234";
for( var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
makeid();
textArray = text.split("");
console.log(textArray);
function animate1() {
$('#btn' + textArray[0]).animate( { backgroundColor: 'red' }, 500);
}
function animate2() {
$('#btn' + textArray[1]).animate( { backgroundColor: 'red' }, 500);
}
function animate3() {
$('#btn' + textArray[2]).animate( { backgroundColor: 'red' }, 500);
}
function animate4() {
$('#btn' + textArray[3]).animate( { backgroundColor: 'red' }, 500);
}
window.setTimeout(animate1, 1000);
window.setTimeout(animate2, 2000);
window.setTimeout(animate3, 3000);
window.setTimeout(animate4, 4000);
Your issue about shuffling the possible text, because in your function there is a possibility that same number repeated. like: 2,2,2,1 or 4,4,4,4 and so on.
you can use this shuffle function instead of your method of shuffling:
function shuffleWord(word) {
var shuffledWord = '';
var charIndex = 0;
word = word.split('');
while (word.length > 0) {
charIndex = word.length * Math.random() << 0;
shuffledWord += word[charIndex];
word.splice(charIndex, 1);
}
return shuffledWord;
}
See JsFiddle of your example after updates.
You can't animate backgroundColor unless the jQuery.Color plugin is used, jQuery animate docs
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be, unless the
jQuery.Color plugin is used).
And you allow duplicate IDs when creating the random order. Also, the code can be simplified.
var textArray = [];
function makeid() {
var num;
var possible = "1234";
while(textArray.length < 4) {
num = possible.charAt(Math.floor(Math.random() * possible.length));
if (textArray.indexOf(num) === -1) {
textArray.push(num)
}
}
}
function animate(id, wait) {
setTimeout(function() {
$('#btn' + id).animate({ width: '200'}, 500);
}, wait);
}
makeid();
for (var i=0; i < textArray.length; i++) {
animate(textArray[i], i * 1000)
}
fiddle

Categories

Resources