Tweet text from a page - javascript

I want to take some text from the HTML page and tweet it out.
Here is my HTML page -
function change() {
quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"];
auth = ["Raj", "Mogambo", "Gabbar"];
min = 0;
max = 3;
num = Math.floor(Math.random() * (max - min)) + min;
q = quotes[num]
document.getElementById("quote").innerHTML = quotes[num];
document.getElementById("author").innerHTML = auth[num];
if (num == 0) {
document.getElementById("bod").style.color = 'white';
document.body.style.backgroundColor = 'green';
document.getElementById("another").style.backgroundColor = 'green';
document.getElementById("tweet").style.backgroundColor = 'green';
}
if (num == 1) {
document.getElementById("bod").style.color = 'black';
document.body.style.backgroundColor = 'yellow';
document.getElementById("another").style.backgroundColor = 'yellow';
document.getElementById("another").style.color = 'black';
document.getElementById("tweet").style.color = 'black';
document.getElementById("tweet").style.backgroundColor = 'yellow';
}
if (num == 2) {
document.getElementById("bod").style.color = 'white';
document.body.style.backgroundColor = 'blue';
document.getElementById("another").style.backgroundColor = 'blue';
document.getElementById("tweet").style.backgroundColor = 'blue';
}
}
function twitter() {
text = document.getElementById('quote').innerHTML;
// document.getElementById('tw').innerHTML = text;
$('.twitter-button').attr("href", 'https://twitter.com/intent/tweet?text=' + text);
};
<body id='bod'>
<h1>Quotes</h1>
<div class='text'>
<p id='quote'>You're fired!</p>
<br>
<p id='author'>Vince McMahon</p>
<button id='another' class='btn btn-primary' onclick='change()'>Another Quote</button>
<br>
<br>
<a class="twitter-button" href="https://twitter.com/intent/tweet?text=" target="_blank">
<button type="button" onclick='twitter()' class="btn btn-primary" id='tw'>Tweet!</button>
</a>
Whenever I click on the tweet button, there is no text on the twitter page. Just a blank box.
Link to Codepen - https://codepen.io/pranavgoel25/pen/ZybNRv?editors=1010

I have tweeked a code bit:
var quotes = ["Naam toh suna hi hoga","Mogambo Khush Hua","Kitne aadmi the?"];
function change(){
auth = ["Raj","Mogambo","Gabbar"];
min = 0;
max = 3;
num = Math.floor(Math.random() * (max - min)) + min;
q = quotes[num]
document.getElementById("quote").innerHTML = quotes[num];
document.getElementById("author").innerHTML = auth[num];
document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[num]);
if (num == 0){
document.getElementById("bod").style.color='white';
document.body.style.backgroundColor = 'green';
document.getElementById("another").style.backgroundColor='green';
document.getElementById("tweet").style.backgroundColor='green';
}
if (num == 1){
document.getElementById("bod").style.color='black';
document.body.style.backgroundColor = 'yellow';
document.getElementById("another").style.backgroundColor='yellow';
document.getElementById("another").style.color='black';
document.getElementById("tweet").style.color='black';
document.getElementById("tweet").style.backgroundColor='yellow';
}
if (num == 2){
document.getElementById("bod").style.color='white';
document.body.style.backgroundColor = 'blue';
document.getElementById("another").style.backgroundColor='blue';
document.getElementById("tweet").style.backgroundColor='blue';
}
}
window.onload = function(){
document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[0]);
}
Working Demo:
https://codepen.io/anon/pen/BZjQBe?editors=1010

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

Play audio file based on id from mysql database

I have this audio player script that plays audio files, but i don't know how to play the files individually based on id from mysql database. I have a datatable and all the files listed there with a play button to make an idea. Thanks
Codepen audio player script:
https://codepen.io/abxlfazl/pen/YzGEVRP
Here is the audio script:
PHP:
<?php
$qnm = $db->query("SELECT * FROM `".RDCP_PREFIX."muzica` WHERE uid = ".$uid." ");
while ($row = $db->fetch($qnm)) {
$id = $row['mid']; // music id
$locatiem = $row['locatie'];
$numeclubs = $row['numeclub'];
$numecoregrafiem = $row['numecoregrafie'];
$piesa = str_replace("muzica/", "", $locatiem); // music file track
?>
HTML:
<div class="modal plyer fade delmusic<?php echo $id;?>" tabindex="-1" id="delmusic<?php echo $id; ?>"
track="<?php echo $id;?>" aria-labelledby="myDefaultModalLabel">
<div class="container" style="margin-top: 332px;display: flex;">
<div class="player">
<div class="player__header">
<div class="player__img player__img--absolute slider">
<button class="player__button player__button--absolute--nw playlist">
<img src="../../../dt/app-assets/images/elements/musicplayer/playlist.svg" alt="playlist-icon">
</button>
<button class="player__button player__button--absolute--center play">
<img src="../../../dt/app-assets/images/elements/musicplayer/play.svg" alt="play-icon">
<img src="../../../dt/app-assets/images/elements/musicplayer/pause.svg" alt="pause-icon">
</button>
<div class="slider__content">
<img class="img slider__img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
</div>
</div>
<div class="player__controls">
<button class="player__button back">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/back.svg" alt="back-icon">
</button>
<p class="player__context slider__context">
<strong class="slider__name"></strong>
<span class="player__title slider__title"></span>
</p>
<button class="player__button next">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/next.svg" alt="next-icon">
</button>
<div class="progres">
<div class="progres__filled"></div>
</div>
</div>
</div>
<ul class="player__playlist list">
<li class="player__song s<?php echo $id;?>">
<img class="player__img img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
<p class="player__context">
<b class="player__song-name"><?php echo $numecoregrafiem; ?></b>
<span class="flex">
<span class="player__title"><?php echo $numeclubs; ?></span>
</span>
</p>
<audio class="audio" src="<?php echo "dt/pagini/momente/momente/".$locatiem; ?>"></audio>
</li>
</ul>
</div>
</div>
</div>
Javascript:
const bgBody = ["#e5e7e9", "#ff4545", "#f8ded3", "#ffc382", "#f5eda6", "#ffcbdc", "#dcf3f3"];
const body = document.body;
const player = document.querySelector(".player");
const playerHeader = player.querySelector(".player__header");
const playerControls = player.querySelector(".player__controls");
const playerPlayList = player.querySelectorAll(".player__song");
const playerSongs = player.querySelectorAll(".audio");
const playButton = player.querySelector(".play");
const nextButton = player.querySelector(".next");
const backButton = player.querySelector(".back");
const playlistButton = player.querySelector(".playlist");
const slider = player.querySelector(".slider");
const sliderContext = player.querySelector(".slider__context");
const sliderName = sliderContext.querySelector(".slider__name");
const sliderTitle = sliderContext.querySelector(".slider__title");
const sliderContent = slider.querySelector(".slider__content");
const sliderContentLength = playerPlayList.length - 1;
const sliderWidth = 100;
let left = 0;
let count = 0;
let song = playerSongs[count];
let isPlay = false;
const pauseIcon = playButton.querySelector("img[alt = 'pause-icon']");
const playIcon = playButton.querySelector("img[alt = 'play-icon']");
const progres = player.querySelector(".progres");
const progresFilled = progres.querySelector(".progres__filled");
let isMove = false;
function closePlayer() {
playerHeader.classList.remove("open-header");
playerControls.classList.remove("move");
slider.classList.remove("open-slider");
}
function next(index) {
count = index || count;
if (count == sliderContentLength) {
count = count;
return;
}
left = (count + 1) * sliderWidth;
left = Math.min(left, (sliderContentLength) * sliderWidth);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count++;
run();
}
function back(index) {
count = index || count;
if (count == 0) {
count = count;
return;
}
left = (count - 1) * sliderWidth;
left = Math.max(0, left);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count--;
run();
}
function changeSliderContext() {
sliderContext.style.animationName = "opacity";
sliderName.textContent = playerPlayList[count].querySelector(".player__title").textContent;
sliderTitle.textContent = playerPlayList[count].querySelector(".player__song-name").textContent;
if (sliderName.textContent.length > 16) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderName.textContent + " " + sliderName.textContent;
sliderName.innerHTML = "";
sliderName.append(textWrap);
}
if (sliderTitle.textContent.length >= 18) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderTitle.textContent + " " + sliderTitle.textContent;
sliderTitle.innerHTML = "";
sliderTitle.append(textWrap);
}
}
function selectSong() {
song = playerSongs[count];
for (const item of playerSongs) {
if (item != song) {
item.pause();
item.currentTime = 0;
}
}
if (isPlay) song.play();
}
function run() {
changeSliderContext();
selectSong();
}
function playSong() {
if (song.paused) {
song.play();
playIcon.style.display = "none";
pauseIcon.style.display = "block";
}else{
song.pause();
isPlay = false;
playIcon.style.display = "";
pauseIcon.style.display = "";
}
}
function progresUpdate() {
const progresFilledWidth = (this.currentTime / this.duration) * 100 + "%";
progresFilled.style.width = progresFilledWidth;
if (isPlay && this.duration == this.currentTime) {
next();
}
if (count == sliderContentLength && song.currentTime == song.duration) {
playIcon.style.display = "block";
pauseIcon.style.display = "";
isPlay = false;
}
}
function scurb(e) {
// If we use e.offsetX, we have trouble setting the song time, when the mousemove is running
const currentTime = ( (e.clientX - progres.getBoundingClientRect().left) / progres.offsetWidth ) * song.duration;
song.currentTime = currentTime;
}
function durationSongs() {
let min = parseInt(this.duration / 60);
if (min < 10) min = "0" + min;
let sec = parseInt(this.duration % 60);
if (sec < 10) sec = "0" + sec;
const playerSongTime = `${min}:${sec}`;
}
changeSliderContext();
// add events
sliderContext.addEventListener("animationend", () => sliderContext.style.animationName ='');
playlistButton.addEventListener("click", closePlayer);
nextButton.addEventListener("click", () => {
next(0)
});
backButton.addEventListener("click", () => {
back(0)
});
playButton.addEventListener("click", () => {
isPlay = true;
playSong();
});
playerSongs.forEach(song => {
song.addEventListener("loadeddata" , durationSongs);
song.addEventListener("timeupdate" , progresUpdate);
});
progres.addEventListener("pointerdown", (e) => {
scurb(e);
isMove = true;
});
document.addEventListener("pointermove", (e) => {
if (isMove) {
scurb(e);
song.muted = true;
}
});
document.addEventListener("pointerup", () => {
isMove = false;
song.muted = false;
});
playerPlayList.forEach((item, index) => {
item.addEventListener("click", function() {
if (index > count) {
next(index - 1);
return;
}
if (index < count) {
back(index + 1);
return;
}
});
});
You could put the track ID into an attribute like "data-track" then retrieve it and send out an ajax request to a php page which will do your DB query and return the info you want.
// User selects track to play
$(".track").on('click', function(e){
track = $(this).data("track");
var data = {
trackId: track
};
$.ajax({
url: 'getTrack.php',
type: 'post',
data: data,
}).done(function(result){
// parse data from response and load your player's modal
}).fail(function(data){
// Uh-oh!
}).always(function(){
// Do something
});
});

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

Automate checking process

The code below returns me 'even' or 'odd', but I have to always change, what to do for him to check 25 to 115 and show result in the body of the page?
<html>
<title>FrontPage</title>
</head>
<body>
<form method="post" name="Form1" onsubmit="Check();">
<input type="submit" value="Submit" name="bSubmit"></p>
</form>
<script type="text/javascript">
function Check() {
var n = "26";
var finish = n/2;
if(n & 1){
alert("Impar");
} else {
alert("Par");
}
alert(finish);
}
</script>
</body>
</html>
var btn = document.querySelector('#btn');
var result = document.querySelector('#result');
btn.addEventListener('click', function() {
for (var i = 25; i <= 115; i++) {
var li = document.createElement('li');
li.innerText = i.toString() + ' - ' + ((i & 1) ? 'Impar' : 'Par');
result.append(li);
}
});
<input id="btn" type="submit" value="Submit" name="bSubmit">
<ul id="result"></ul>
Just implement your code within a for-loop (since you know exactly how many iterations you need):
document.querySelector('#btnSubmit').addEventListener('click', function(e) {
var min = 25;
var max = 115;
var i;
for (i = min; i <= max; i += 1) {
console.log(check(i));
}
});
function check(n) {
var s = `${n} is `;
s += n % 2 === 0 ? "even" : "odd";
return s;
}
check();
<input id="btnSubmit" type="button" value="Check" />
You need to use the foor loop like so:
const append = str => document.getElementById('print').innerHTML += str;
document.getElementById('btn').addEventListener('click', function () {
for (let i = 25; i <= 115; i++) {
const result = i % 2 === 0 ? 'even' : 'odd';
append(`<p>Number ${i} is ${result}</p>`);
}
});
<button id="btn">Result</button>
<div id="print"></div>

javascript variables and functions with arrays for each html formel

is it possible to reuse this javascript
<script>
var speed = 100;
var gold = 0;
gold = parseFloat(gold.toFixed(2));
var production = 10;
production = parseFloat(production.toFixed(0));
var price = 100;
price = parseFloat(price.toFixed(2));
document.getElementById("speed").innerHTML=speed;
document.getElementById("gold").innerHTML = gold;
document.getElementById("production").innerHTML=production;
document.getElementById("price").innerHTML=price;
function dig() {
var elem = document.getElementById("bar");
var width = 0;
var id = setInterval(frame, speed);
function frame() {
if (width >= 100) {
clearInterval(id);
elem.style.width = '0%';
gold = gold + production;
gold = parseFloat(gold.toFixed(2));
document.getElementById("dig").disabled = false;
document.getElementById("gold").innerHTML = gold;
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
} else {
width++;
elem.style.width = width + '%';
document.getElementById("dig").disabled = true;
}
}
}
$(document).ready(function priceUpgrade() {
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
});
$(document).ready(function upgrade(){
$("#upgrade").click(function(){
speed = speed - 10;
gold = gold - price;
gold = parseFloat(gold.toFixed(2));
production += production * 0.10;
production = parseFloat(production.toFixed(0));
price += price * 0.50;
price = parseFloat(price.toFixed(2));
document.getElementById("speed").innerHTML=speed;
document.getElementById("gold").innerHTML=gold;
document.getElementById("production").innerHTML=production;
document.getElementById("price").innerHTML=price;
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
});
});
</script>
with a new value in the variables speed, gold and production for each new html line of these
<div id="speed">100</div>
<div class="row">
<div class="col-md-2">
<div id="production"></div>
<button type="button" class="btn btn-success" onclick="dig()" id="dig">Gull Sil</button>
</div>
<div class="col-md-7">
<div id="progress">
<div id="bar"></div>
</div>
</div>
<div class="col-md-3">
<div id="price"></div>
<button type="button" class="btn btn-warning" onclick="upgrade()" id="upgrade">Oppgrader</button>
</div>
</div>
so each time a call speed[3] or dig(3) both the variables and the functions response different to each key=>value in an array or some how??
maybe var speed {1:10,2:30,3:70,4:150};
and dig([1,2,3,4]);

Categories