Need help creating a button to activate a javascript function - javascript

This is my script, I am trying to make a button randomize the images instead of me having to press the refresh button. What exactly do I need to code the button as to make this work?
My code
I think I am confused on what my function name is? I had a lot of help creating this so I'm a bit lost on what to do as far as the button is. I've created a button and I've tried plugging in multiple things for the "onclick" but nothing works.
<!doctype html>
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
(function () {
var theImages = [{
src: "winry doe.gif",
width: "480",
height: "270"
}, {
src: "WINRY WINK.gif",
width: "500",
height: "484"
}, {
src: "winry getting hugged.gif",
width: "500",
height: "205"
},
{
src: "winry getting mad.gif",
width: "500",
height: "292"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
<form>
<input type="button" value="More Winry" onclick="">
</form>
</body>
</html>

Just add :
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
and to the button onclick add:
<input type="button" value="More Winry" onclick="randomImage()">
EDIT
To replace existing image:
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
var img = document.getElementsByTagName('img').remove();
document.body.appendChild(newImage);
};
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
add those function instead.
Credits to JavaScript: remove element by id
also, no need of JQuery in functions so JQuery tag is useless.

You can also use similar to this (as long as the img's have that class). Using the prototype method described by Edan Feiles answer
the button html:
<form>
<input id="imageButton" type="button" value="More Winry" />
</form>
and the JS:
var button = document.getElementById("imageButton");
button.onclick = function() {
var newImage = getRandomImage();
console.log(newImage);
document.getElementsByClassName("atvi-image-image").remove();
document.body.appendChild(newImage);
};
or you can use what Edan Feiles said and just add this line to the function:
document.getElementsByClassName("atvi-image-image").remove();
before adding the new random image.

Related

How do I add an image to an if statement in Javascript?

I'm new at JavaScript to be patient with me. I'm trying to get this little "game" to work where you drag cards in the drop box, and when you drop the joker card in it says "victory", otherwise it says "betrayal" for the other cards. Everything works great except the part where it says "victory" when you drop the joker. I feel like I have tried everything. The joker card is $(#black_joker)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop</title>
<link rel="stylesheet" href="dragdrop.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<h1>Find the Joker and eliminate him!</h1>
<br>
<input type="button" value="Deal!" id="dealDeck">
<br>
<br>
<br>
<br>
<br>
<div id='dropZone' class='dropZone'> <center>Find the joker card and drop it here to get rid of him once and for all! </center></div>
<script src="dragdrop.js"></script>
</body>
</html>
// JAVASCRIPT
$(document).ready(function () {
$(init);
function init() {
$('.dropZone').droppable({
drop: handleDropEvent
});
}
for (var a=0, all = 53; a < all; a++){
$('#dealDeck').click(function () {
dealCard(randomCard());
});
}
var cardsInDeck = new Array();
var numberOfCardsInDeck = 53;
cardsInDeck[0] = "C1";
cardsInDeck[1] = "C2";
cardsInDeck[2] = "C3";
cardsInDeck[3] = "C4";
cardsInDeck[4] = "C5";
cardsInDeck[5] = "C6";
cardsInDeck[6] = "C7";
cardsInDeck[7] = "C8";
cardsInDeck[8] = "C9";
cardsInDeck[9] = "C10";
cardsInDeck[10] = "C11";
cardsInDeck[11] = "C12";
cardsInDeck[12] = "C13";
cardsInDeck[13] = "D1";
cardsInDeck[14] = "D2";
cardsInDeck[15] = "D3";
cardsInDeck[16] = "D4";
cardsInDeck[17] = "D5";
cardsInDeck[18] = "D6";
cardsInDeck[19] = "D7";
cardsInDeck[20] = "D8";
cardsInDeck[21] = "D9";
cardsInDeck[22] = "D10";
cardsInDeck[23] = "D11";
cardsInDeck[24] = "D12";
cardsInDeck[25] = "D13";
cardsInDeck[26] = "H1";
cardsInDeck[27] = "H2";
cardsInDeck[28] = "H3";
cardsInDeck[29] = "H4";
cardsInDeck[30] = "H5";
cardsInDeck[31] = "H6";
cardsInDeck[32] = "H7";
cardsInDeck[33] = "H8";
cardsInDeck[34] = "H9";
cardsInDeck[35] = "H10";
cardsInDeck[36] = "H11";
cardsInDeck[37] = "H12";
cardsInDeck[38] = "H13";
cardsInDeck[39] = "S1";
cardsInDeck[40] = "S2";
cardsInDeck[41] = "S3";
cardsInDeck[42] = "S4";
cardsInDeck[43] = "S5";
cardsInDeck[44] = "S6";
cardsInDeck[45] = "S7";
cardsInDeck[46] = "S8";
cardsInDeck[47] = "S9";
cardsInDeck[48] = "S10";
cardsInDeck[49] = "S11";
cardsInDeck[50] = "S12";
cardsInDeck[51] = "S13";
cardsInDeck[52] = "black_joker";
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var img = document.createElement("img");
img.src = "http://deetito.com/images/" + cardsInDeck[i] + ".png";
img.id = cardsInDeck[i];
img.width = 100;
img.height = 125;
document.body.appendChild(img);
$('#C1').draggable();
$('#C2').draggable();
$('#C3').draggable();
$('#C4').draggable();
$('#C5').draggable();
$('#C6').draggable();
$('#C7').draggable();
$('#C8').draggable();
$('#C9').draggable();
$('#C10').draggable();
$('#C11').draggable();
$('#C12').draggable();
$('#C13').draggable();
$('#D1').draggable();
$('#D2').draggable();
$('#D3').draggable();
$('#D4').draggable();
$('#D5').draggable();
$('#D6').draggable();
$('#D7').draggable();
$('#D8').draggable();
$('#D9').draggable();
$('#D10').draggable();
$('#D11').draggable();
$('#D12').draggable();
$('#D13').draggable();
$('#H1').draggable();
$('#H2').draggable();
$('#H3').draggable();
$('#H4').draggable();
$('#H5').draggable();
$('#H6').draggable();
$('#H7').draggable();
$('#H8').draggable();
$('#H9').draggable();
$('#H10').draggable();
$('#H11').draggable();
$('#H12').draggable();
$('#H13').draggable();
$('#S1').draggable();
$('#S2').draggable();
$('#S3').draggable();
$('#S4').draggable();
$('#S5').draggable();
$('#S6').draggable();
$('#S7').draggable();
$('#S8').draggable();
$('#S9').draggable();
$('#S10').draggable();
$('#S11').draggable();
$('#S12').draggable();
$('#S13').draggable();
$('#black_joker').draggable();
removeCard(i);
}
function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);
}
function handleDropEvent(event, ui) {
var card = ui.draggable;
if (card == 'black_joker') {
$('#dropZone').html('victory!');}
else {
$('#dropZone').html('betrayal!');}
/*$('#dropZone').droppable({
drop: function(event, ui) {
ui.draggable.remove();
}
});*/
$("#dropZone").on('mouseover', function() {
//alert('bye draggable!');
//ui.draggable.draggable('disable');
//$(this).droppable('disable');
ui.draggable.remove();
})
}
function removeCard(c) {
// simply make every higher numbered card move down 1
for (j = c; j <= numberOfCardsInDeck - 2; j++) {
cardsInDeck[j] = cardsInDeck[j + 1];
}
numberOfCardsInDeck--;
}
});
I believe you are comparing object with string.
ui.draggable should be jQuery object
let card = ui.draggable.attr("id");
compare it with your id or other attribute you wanted to use should work

How to make 1 block javascript experiment into 2 blocks that presents data at the end of the 2nd block and then save data to a local sever using MAMP

My goal for this experiment is to have 2 blocks of trials, both which flash 10 words and then the participants have to click yes or no if they saw the word or not (answer yes or no to 20 words). After the 2 blocks I would like the data to be displayed and the experiment to end, although right now the experiment is infinite and displays data after every block. I also need to know how to save the data with a "Save Data" button after presenting both of the blocks data at the end. Any and all help appreciated!
If anyone has any ideas about how to create two blocks, as I have tried to initiate by declaring blocks = 0 at the beginning it would be greatly appreciated!
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="342.js" type="text/javascript"></script>
<script type="text/javascript">
let index = 0, blocks=0;
let words = ["fox", "tree", "wheel", "pillow", "target", "wool", "bread", "sport", "dog", "straw", "state",
"mountain", "cot" , "green" , "napkin" , "grape" , "glass" , "drum" , "grass",];
let stimuli = [];
let N = words.length/2;
let t;
window.onload = initialize;
function initialize() {
for (let i = 0; i < words.length; i++) {
stimuli.push(new Stimulus(words[i]));
}
shuffle(stimuli);
for (let i = 0; i < words.length; i++) {
if (i < N) {
stimuli[i].presented = "1";
stimuli[i].presOrder = i;
}
else {
stimuli[i].presented = "0";
stimuli[i].presOrder = "-1"
}
}
}
function Stimulus(word) {
this.word = word;
}
Stimulus.prototype.toString = function () {
return "\t Order Presented: " + this.presOrder + "\t Order tested: " + this.testOrder + "\t Word Presented:" + this.word + "\t Response (0 or 1):"
+ this.resp + " \t Presented (0 or 1):" + this.presented;
};
function begin() {
document.getElementById("b").style.visibility = "hidden";
document.getElementById("word").innerHTML = "";
t = setInterval(nextWord, 250)
}
function nextWordTest() {
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].testOrder = index;
if (blocks=1)
{
document.getElementById("b2").style.visibility = "visible";
}
}
function nextWord()
{
if (index < N)
{
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].presOrder = index;
index++;
}
else
{
clearInterval(t);
document.getElementById("word").innerHTML = "Click yes if you saw the word and " +
"no if you did not see the word";
document.getElementById("yes").style.visibility = "visible";
document.getElementById("no").style.visibility = "visible";
document.getElementById("b2").style.visibility = "hidden";
index = 0;
N = words.length;
stimuli = shuffle(stimuli);
nextWordTest();
}
}
function record(resp) {
stimuli[index].resp = resp;
index++;
if (index < N) {
nextWordTest();
}
else {
if (blocks===0){
nextWordTest()
}
if (blocks===1)
{
document.getElementById("word").innerHTML = "finished";
data = "";
for (let i = 0; i < stimuli.length; i++)
{
data += stimuli[i] + "\n";
}
console.log(data);
document.getElementById("word").innerText = data;
}
}
}
</script>
</head>
<body>
<h1> Attentional Blink Experiment </h1>
<p id="word">Push button to begin.</p>
<button type="button" id="yes" onclick="record(1)" style="visibility: hidden">yes</button>
<button type="button" id="no" onclick="record(0)" style="visibility: hidden">no</button>
<button type="button" id="b" onclick="begin()">Begin</button>
<button type="button" id="b2" onclick="begin()" style="visibility: hidden">Continue</button>
</body>
</html>

onclick: picture does not change

My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>

how to show value without clicking on submit button

I am using html5 and javascript .I am reading excel file from java script and showing output..PLease analyze my code first
<input type="button" id="btnSubmit" onclick="readdata(1, 2)" value="Submit" />
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open("D:\\Test.xls");// alert(excel_file.worksheets.count);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
Now I'm reading the file from this code and showing the output with this code:
function drawWithexcelValue(val) {
var txtSpeed = val; //alert(txtSpeed.value);
if (txtSpeed !== null) {
iTargetSpeed = txtSpeed;
// Sanity checks
if (isNaN(iTargetSpeed)) {
iTargetSpeed = 0;
} else if (iTargetSpeed < 0) {
iTargetSpeed = 0;
} else if (iTargetSpeed > 80) {
iTargetSpeed = 80;
}
job = setTimeout("draw()", 5);
}
}
Q .1 every time i click on the submit button it show me the value from excel file ,i want that i didn't have to click every time on submit button ..it automatically show the values at some time interval for say 4 seconds.
Q :-2 I didn't want the submit button ,that means when i run this code it automaticaly start running the script say onload ="readdata(1, 2)" ,but it is showing only one value ...how to show all values with some time interval ..please help!!!!!
Guys if you can give me edited code than it really will be help full for me
here this code will surely work for ya
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js">
</script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div id="divHidden" style="visibility: hidden; width: 0px; height: 0px">
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type="file" id="file" onchange="checkfile(this);" />
<input type="button" id="btnSubmit" onclick="readdata(1, 2)" value="Submit" />
<button onclick="myStopFunction()">Stop Meter</button>
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
var myVar=setInterval(function(){readdata(1,2)},2000);
function myStopFunction()
{
clearInterval(myVar);
}
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open("D:\\Test.xls");// alert(excel_file.worksheets.count);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
if(data==null || data=="")
{
myStopFunction();
}
excel.Application.Quit();
}
catch (ex) {
alert(ex);
}
}
</script>

Javascript 4-image slideshow w/ arrays & setTimeout

<script type=text/javascript>
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
for(var i = 0, l = topLeftImages.length; i < l; i++)
{
setTimeout(function()
{
document.getElementById('myimage1').src = "images\\" + "op.jpg";
document.getElementById('myimage2').src = "images\\" + topRightImages[i];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[i];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[i];
}, 10000);
}
</script>
Associated HTML:
<img id="myimage1" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage2" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage3" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage4" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
This code is meant to show four images, and every 10 seconds, switch all four images simultaneously, going through all of my images in my four arrays. The images are in the images/ directory above my HTML file that contains this code. For testing purposes, I changed myimage1 to change to op.jpg only. This works and correctly shows op.jpg. However, when querying the arrays, instead of the file names, I get undefined. That is problem number one.
Problem number two, when I change my for loop to a more normal looking one like:
for(var i = 0; i < l2; i++)
The script stops working entirely (doesn't show op.jpg and doesn't even try to change the images)... what the hell!
I'm using Firefox and Google Chrome for testing purposes.
I suggest something like that instead:
<script type=text/javascript>
$(document).ready(function () {
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
var i = 0;
var max = 12;
setInterval(function()
{
var index = i % max;
document.getElementById('myimage1').src = "images\\" + topLeftImages[index];
document.getElementById('myimage2').src = "images\\" + topRightImages[index];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[index];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[index];
i++;
}, 10000);
});
</script>
jsFiddle with some example images http://jsfiddle.net/ApfJz/8/

Categories