How to assign heart icon to beats per minute counter javascript - javascript

To start of, I would like to notify that I am pretty new to javascript, I hope you will bear with me.
I have this code that on mouse down it counts the beats per minute. What I would like to do is display a Heart Icon in the space of the division so that when someone clicks the heart it will display the BPM.
This is what I have now:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="tapDiv" style="height:200px;width:200px;background-color:#000;color:#FFF"></div>
<script>
lastTapSeconds = 0;
bpm = 0;
var tapDiv = document.getElementById("tapDiv");
function bpmCounter() {
var tapSeconds = new Date().getTime();
bpm = ((1 / ((tapSeconds - lastTapSeconds) / 1000)) * 60);
lastTapSeconds = tapSeconds;
tapDiv.innerHTML = "<h1>" + Math.floor(bpm) + "</h1>";
}
tapDiv.onmousedown = bpmCounter;
</script>
</body>
</html>
How do I implement a heart icon (image) so that it will display that and interact with the js?
I though perhaps I could enter a source in the division and direct to the heart.png in my directory so that it will display that and work with the tapDiv id. But I am not sure of this.
I hope I have given you enough info.
thanks
Mieer

The Simple Way:
Replace:
tapDiv.innerHTML = "<h1>" + Math.floor(bpm) + "</h1>";
with:
tapDiv.innerHTML = '<h1 style="display:inline">' + Math.floor(bpm) + '</h1><img src="/Images/heart.png"/>';
//specify your own source path for heart.png
this simply adds an image element to your dynamically created content and is probably the easiest to implement with your current code set:
Working Fiddle
Alternate Way:
You can use CSS to set an image by specifying a class, and this is the more preferred method: how to put an image in div with css

Related

Define image size with random image code?

At the moment I'm working with Elementor on Wordpress. What I'd like to do is have one of "modules" in Elementor filled with random images that also have each a different link to some page. I looked for a random image widget but those I found didn't provide a function to define a different link for each randomized image. So I decided to use the html widget on Elementor to use my own code. I'm not super skilled at this. So I have a code, the randomizing is working, so are the links but I don't know how to define a max. width for the images because they just fill the whole page with this code. My english isn't very good I hope someone might be able to help me and where to put something in the code to define the images size?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var imageUrls = [
"IMAGE1“
, "IMAGE2“
, "IMAGE3“
];
var imageLinks = [
"LINK1“
, "LINK2“
, "LINK3“
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"\"/></a>';
return img;
}
</script>
</head>
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>

Why does my JavaScript code not work on refresh?

I'm taking a Udemy course and one of the exercises is to build a Dice game.
Basically it's just two dice (for each player/stakeholder) on screen both showing the value of 6. On refresh, it should 'roll' the dice (generate a random side for each dice, which are all images), and the header text should change to state the outcome of the game.
But my code doesn't work on refresh. I'm trying to find out why. Here's a comparison of my code VS the instructor's code:
This is my code, which doesn't work on refresh (but I've tested it and it works when I run it as a function).
//Generating Random Numbers for Dice 1 & Dice 2
var RandomNo1 = (Math.floor(Math.random() * 6) + 1)
var RandomNo2 = (Math.floor(Math.random() * 6) + 1)
//Making a var for image sources Dice 1-6 (images/dice#.png)
var imageSource1 = ("images/dice" + RandomNo1 + ".png")
var imageSource2 = ("images/dice" + RandomNo2 + ".png")
//set.Attribute function to change the img source for the dice
document.querySelector('.player1').setAttribute("src", imageSource1);
document.querySelector('.player2').setAttribute("src", imageSource2);
//Setting conditional statements to change the header depending on results of the dice roll.
if (RandomNo1 > RandomNo2) {
document.querySelector("h1").innerText="Player 1 Wins!";
}
else if (RandomNo2 > RandomNo1) {
document.querySelector("h1").innerText="Player 2 Wins!";
}
else {
document.querySelector("h1").innerText="It's a draw!";
}
This is the instructor's code, which does work on refresh.
var randomNumber1 = Math.floor(Math.random() * 6) + 1; //1-6
var randomDiceImage = "dice" + randomNumber1 + ".png"; //dice1.png - dice6.png
var randomImageSource = "images/" + randomDiceImage; //images/dice1.png - images/dice6.png
var image1 = document.querySelectorAll("img")[0];
image1.setAttribute("src", randomImageSource);
var randomNumber2 = Math.floor(Math.random() * 6) + 1;
var randomImageSource2 = "images/dice" + randomNumber2 + ".png";
document.querySelectorAll("img")[1].setAttribute("src", randomImageSource2);
//If player 1 wins
if (randomNumber1 > randomNumber2) {
document.querySelector("h1").innerHTML = "🚩 Play 1 Wins!";
}
else if (randomNumber2 > randomNumber1) {
document.querySelector("h1").innerHTML = "Player 2 Wins! 🚩";
}
else {
document.querySelector("h1").innerHTML = "Draw!";
}
How does her page change on refresh? Why doesn't it change immediately upon loading? Why doesn't my code, like hers, work on refresh?
Your script is fine. In essence it does the same as the script your teacher provided. To be honest, your script is better on several aspects, not in the least because you have added explanatory comments throughout, and I really like to see someone using .innerText, and not .innerHTML. The latter is really intended to inject HTML, so you did right to opt for .innerText. Personally, I would use .textContent, but that is just a detail.
The only explanation that is left, is that your script runs too soon, when the DOM is not ready yet, and so the querySelector() calls return undefined.
Move your <script> element towards the end of your HTML document, after the other elements you need to address in your script. A good place to put it, is right before the closing </body> tag.
welcome to stackoverflow!
There are a few mistakes in your code:
Do not begin your variable names with capital lettes, these are for naming constructors. (It's some sort of unspoken law to make your code better readable for other developers as well)
I don't think this is a problem in your code you showed us. I think you should
paste the script tag on the end of the html file, so document.querySelector() can select the html elements.
I made a pen here where I took your code and show you that it works. (I just changed the $element.setAttribute("src") to $element.innerText)
You can also use $element.src = instead of $element.setAttribute("src")

Unable to modify javascript within an HTML website

Hello I am relatively new and have never coded before a month ago but I am slowly teaching myself the structure and inner workings of a website though html, css, and javascript. I am trying to modify a specific script within a website. This website is
https://www.wizards.com/dnd/dice/dice.htm
My goal is to make it so that I can manipulate a dice roll to give me an altered range for example instead of 1-4, maybe 1-10 and to also perhaps give me a number I specify. I also want to leave the general aesthetic of the site as unchanged as possible.
So first off I put this handy piece of code within the URL
javascript:document.body.contentEditable='true'; document.designMode='on'; void 0
and it allowed me to make the content within the body editable.
I wanted to be simple and just change the D4 dice element https://gyazo.com/adf563827f63edd37264882e90fd5f85 so it would give give me numbers in a range of 1-20.
The HTML code for this element is
<img src="https://www.wizards.com/dnd/dice/images/d4a.jpg" alt="d4" name="d4" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('document.d4','document.d4','images/d4b.jpg')" width="38" border="0" height="37">
I noticed the onclick="rolld4()" So I looked within the head of the website and noticed within <script language="JavaScript1.2"></script> these lines of code.
function rolld4() {
d4rolls = parseInt(document.form1.d4n.value);
d4mod = parseInt(document.form1.d4mo.value);
dtotal = "";
d4res = 0;
rtotal = document.form1.runningtotal.value;
for (i=0; i<2; i++) {
if (document.form1.d4m[i].checked) {
d4pm = i }
}
if (d4pm == 0) {
dtotal = dtotal + "Roll(" + d4rolls.toString() + "d4" + ")+" + d4mod.toString() + ":\n"
}
if (d4pm == 1) {
dtotal = dtotal + "Roll(" + d4rolls.toString() + "d4" + ")-" + d4mod.toString() + ":\n"
}
for (r=0; r<d4rolls; r++) {
var d4 = Math.floor((Math.random() * 4) + 1);
d4res = d4res + d4;
dtotal = dtotal + d4.toString() + ","
}
if (d4pm == 0) {
d4res = d4res + d4mod;
dtotal = dtotal + "+" + d4mod + "\n" + "Total:" + d4res
}
if (d4pm == 1) {
d4res = d4res - d4mod;
if (d4res <= minimumvalue) {
d4res = minimumvalue;
}
dtotal = dtotal + "-" + d4mod + "\n" + "Total:" + d4res
}
document.form1.d4r.value = d4res;
rtotal = dtotal + "\n\n" + rtotal;
document.form1.runningtotal.value = rtotal;
}
I altered above line Math.floor((Math.random() * 4) + 1) to Math.floor((Math.random() * 20) + 1)
I then created a new script with the modified code and placed it below the D4 dice element which should alter the output to give me my range from 1-20. I was able to achieve a bit of success and did in fact mimic a roll range of 1-20. However this has only worked for me once and I have been unable to replicate it even going through the exact same process.
I also saw that within the <script language="JavaScript1.2"></script>scripts that it was one large comment. This is what confuses me because if the javascript functions within the code are turned to comments where is the javascript being pulled from when the dice is clicked and "rolled". I cant seem to find the source.
I am a total novice when it comes to javascript I have mostly been delving into HTML and CSS for designing websites so I have practically zero knowledge of javascript beside the general format.
You cannot alter (change) or delete any javascript on a loaded website. It's not possible as web browsers first compile the javascript when website is loading and prepare it for execution.
Even if you delete a script tag, that piece of code exists somewhere in the memory.
BUT, you can add pieces of javascript code to a webpage (think of it as it is adding itself to the end of the page in a separate script tag) via web console or Scratchpad in Mozilla Firefox OR developer tools > console in Google Chrome.
With that and some clever thinking (depending on the existing code on the website) you can do the stuff you want.

Javascript slideshow with interval

I have a JavaScript Slideshow that only changes image when you refresh the page. I've tried adding
setInterval("printImage1()", 4000);
But then I get multiple images underneath eachother.
JavaScript
NumberOfImagesToRotate1 = 10;
FirstPart1 = '<a href="';
MiddlePart1 = '.htm"><img src="img/';
LastPart1 = '.jpg" border="0" height=”450” width="800"></a>';
function printImage1() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate1);
document.write(FirstPart1 + r + MiddlePart1 + r + LastPart1);
}
HTML
<script>printImage1()</script;
If I understand "But then I get multiple images underneath eachother" correctly, then every 4 seconds, you get another image printed under the previous.
in your HTML you should add something like:
<div id="spaceForImage"><div>
Then, in your javascript, include jQuery and replace the document.write(...) line with:
$('#spaceForImage').html(FirstPart1 + r + MiddlePart1 + r + LastPart1);
That should do what you want.
EDIT:
Using Mijago's idea, you'll need to have something like
<a id="slideLink" href="1.htm"><img id="slideImage" src="img/q1.jpg"></img></a>
in your HTML by default, then in your javascript, change document.write() to
$('#slideLink').attr('href',r + '.htm');
$('#slideImage').attr('src','img/' + r + '.jpg');
This is fine too. Changes the DOM less, but has an extra line of code.

Random Images two locations same set

So basically what I am looking for is how to have a random image javascript code but the images are in two different divs but I would like the random images to come from the same array.
I plan to take a JS class this summer so I don't have to ask anymore because I feel like this should be simple...
Currently I am just using the code from javascript kit in two different locations:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
but what I hope to achieve is:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages2[1]="image1a.gif"
myimages[2]="image2.gif"
myimages2[2]="image2a.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0) ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
RENDERED CODE WITHIN DIVS
<div class="one"><img src="img1.gif"></div>
<div class="two"><img src="img1a.gif"></div>
REFRESHED
<div class="one"><img src="img2.gif"></div>
<div class="two"><img src="img2a.gif"></div>
Here's one particular approach.
I start out by identifying all of the variables I plan on using:
var rIndex1, rIndex2,
oContainer1, oContainer2,
aImages;
Now I assign initial references to DOM containers, as well as populate my images array:
oContainer1 = document.getElementById("left");
oContainer2 = document.getElementById("right");
aImages = ['http://placekitten.com/200/200','http://placekitten.com/201/201',
'http://placekitten.com/202/202','http://placekitten.com/203/203',
'http://placekitten.com/204/204','http://placekitten.com/205/205'];
Because I'll be generating random index values a few times, I create a simple function for this logic:
function rIndex ( iMax ) {
return Math.floor( Math.random() * iMax );
}
In order to see the effect over and over, I'm running the logic within an anonymous function, stored within an interval that runs every second. You, of course, could just wrap it up in a named function to be called once.
setInterval(function(){
Setting initial random values for my index variables.
rIndex1 = rIndex( aImages.length );
rIndex2 = rIndex( aImages.length );
We don't want both images to be the same, so as long as we have selected identical values, let's choose another index value for the second index.
while ( rIndex2 == rIndex1 ) rIndex2 = rIndex( aImages.length );
Lastly, I overwrite the innerHTML property of the containers with new image elements.
oContainer1.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex1 ] );
oContainer2.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex2 ] );
}, 1000);
Demo: http://jsbin.com/ubuxoj/edit#javascript,html
This could be improved upon a bit. For instance, it's possible that while aImages[2] is currently being shown in oContainer2, it may be reapplied the next time around. You could check to make sure you only select an image other than that which is currently being displayed in your container.
For what you are wanting to do, I don't see the point to store them on arrays and do complex stuff to get them.
If the URL paths are the same, there is no need to chose them from an array:
function refreshImages() {
var max = 10;
var rand = (Math.floor(Math.random() * max) + 1); //1-10
var src1 = "http://example.com/image" + rand + ".gif";
var src2 = "http://example.com/image" + rand + "a.gif";
document.getElementById("div1").innerHTML = "<img src='" + src1 + "' />";
document.getElementById("div2").innerHTML = "<img src='" + src2 + "' />";
}
window.onload = function() {//need to wait until the divs are loaded
refreshImages();
}​
and in your HTML:
<div id="div1"></div>
<div id="div2"></div>
Note: I added +1 to rand because in your example you started at image1, if you want the possibility to start at image0, just remove the +1 and the range of possibilities will change to 0-9
jsFiddle demo (because the images don't exist, you need to see the source code)
If your purpose is to be extensible (e.g., if you don't know how many images you will have), I would normally recommend appending to the DOM and creating the <div/> randomly as well, and also looping to create the divs so you don't need to create them manually. However, if this is not the case, by using the pattern you have used, you could do something like this:
<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0>'
);
}
var myimages = [
"image1.gif", "image2.gif"
],
myimagesA = [
"image1a.gif", "image2a.gif"
];
</script>
<div class="one"><script>random_imglink(myimages);</script></div>
<div class="two"><script>random_imglink(myimagesA);</script></div>
We first make a random number which we reuse throughout the life of the script on this page load. Then we define the writing function and then make our 2 arrays available so they can be referenced by the function calls within the divs. It's hard to know exactly what you want without more detail, but hopefully this will give some ideas.

Categories