I need to create an audio player, and I can't see how to convert it to javascript.
This is what I have so far...
HTML:
<audio id="music" src="http://www.sousound.com/music/healing/healing_01.mp3"
data-title="Title of the audio" data-author="Author's name"></audio>
<span class="volumeScaleHolder">
<span id="progressBar">
<span id="myVolume"></span>
</span>
</span>
CSS:
#progressBar {
width: 100%;
height: 8px;
background-color: #666666;
display: inline-block;
}
#myVolume {
width: 10%;
height: 100%;
background-color: #B4BB6B;
display:block;
}
border: 0;
}
.volumeScaleHolder {
padding:0;
margin: 3px 0;
}
JAVASCRIPT:
var audio = document.getElementById("music");
var audioVolumeBar = document.getElementById("progressBar");
var myVolumeBar = document.getElementById("myVolume");
var audioVolume = audio.volume;
function volumeAsProgressBar(volume) {
var audioVolumeProgressBar = document.getElementById("progressBar");
var audioVolumeMyBar = document.getElementById("myVolume");
var volume = audioVolume;
var totalVolume = 1;
var minVolume = 0;
var maxVolume = 1;
}
alert(audio.volume);
myVolumeBar.innerHTML = myVolumeBar.innerHTML + volumeAsProgressBar(audioVolume);
I know the javascript is doing nothing. It is because I don't know how to proceed. So what I am trying to do is to check the value of the audio's volume, and then reflect it in the horizontal bar.... It is just some training, so I am not allowed to use any plugin, <progress> or input type range.
I have added width:10% to #myVolume, just to make sure it is there.
Then... I don't know how can I pass the value of the volume (from 0 to 1) to somehow a percentage, because I guess the bar works as a percentage, right?
I don't need anyone giving me the solution code....but some help about what should I think of...
I have made this jsfiddle, although it is quite useless... :(
https://jsfiddle.net/zuL6umjo/1/
To create a bar capable of changing the volume of a audio element here is a code that will help.
var e = document.querySelector('.volume-slider-con');
var eInner = document.querySelector('.volume-slider');
var audio = document.querySelector('audio');
var drag = false;
e.addEventListener('mousedown',function(ev){
drag = true;
updateBar(ev.clientX);
});
document.addEventListener('mousemove',function(ev){
if(drag){
updateBar(ev.clientX);
}
});
document.addEventListener('mouseup',function(ev){
drag = false;
});
var updateBar = function (x, vol) {
var volume = e;
var percentage;
//if only volume have specificed
//then direct update volume
if (vol) {
percentage = vol * 100;
} else {
var position = x - volume.offsetLeft;
percentage = 100 * position / volume.clientWidth;
}
if (percentage > 100) {
percentage = 100;
}
if (percentage < 0) {
percentage = 0;
}
//update volume bar and video volume
eInner.style.width = percentage +'%';
audio.volume = percentage / 100;
};
.volume-slider-con{
height:10px;
width:50%;
position:relative;
background-color:#ddd;
}
.volume-slider{
height:100%;
width:100%;
position:relative;
background-color:red;
}
<audio src="http://www.sousound.com/music/healing/healing_01.mp3" controls></audio>
<div class="volume-slider-con">
<div class="volume-slider"></div>
</div>
Your almost there. Here's an updated fiddle: https://jsfiddle.net/zuL6umjo/8/
Here is a way to expand/shrink your volume bar based off of the volume from the audio element.
function updateVolume () {
myVolumeBar.style.width = audioVolume * 100 + '%';
}
updateVolume();
Related
In my project, there should be a counter.
I want the counter to start when scrolling is done, not when the screen is loading.
I used "reveal" for this, but still the counter starts when the screen loads.
In the project in question, I like when scrolling the page from top to bottom and from bottom to top "reveal" arrives, the counter starts.
How can I solve this problem? Thanks in advance for your guidance.
//counter
const counter = (EL) => {
const duration = 4000; // Animate all counters equally for a better UX
const start = parseInt(EL.textContent, 10); // Get start and end values
const end = parseInt(EL.dataset.counter, 10); // PS: Use always the radix 10!
if (start === end) return; // If equal values, stop here.
const range = end - start; // Get the range
let curr = start; // Set current at start position
const loop = (raf) => {
if (raf > duration) raf = duration; // Stop the loop
const frac = raf / duration; // Get the time fraction
const step = frac * range; // Calculate the value step
curr = start + step; // Increment or Decrement current value
EL.textContent = parseInt(curr, 10); // Apply to UI as integer
if (raf < duration) requestAnimationFrame(loop); // Loop
};
requestAnimationFrame(loop); // Start the loop!
};
document.querySelectorAll("[data-counter]").forEach(counter);
//counter
// reveal
function reveal() {
var reveals = document.querySelectorAll(".reveal");
for (var i = 0; i < reveals.length; i++) {
var windowHeight = window.innerHeight;
var elementTop = reveals[i].getBoundingClientRect().top;
var elementVisible = 10;
if (elementTop < windowHeight - elementVisible) {
reveals[i].classList.add("active");
} else {
reveals[i].classList.remove("active");
}
}
}
window.addEventListener("scroll", reveal);
// reveal
.container{
overflow-y: scroll;
}
.pre-reveal{
width: 100%;
height: 80vh;
border: 1px solid red;
}
/* reveal */
.reveal {
border: 1px solid green;
position: relative;
opacity: 0;
margin-top: 1rem;
}
.reveal.active {
opacity: 1;
}
/* reveal */
<div class="container">
<div class="pre-reveal"></div>
<div class="reveal">
<span>A: </span>
<span data-counter="10">0</span>
<br>
<span>B: </span>
<span data-counter="2022">1000</span>
<br>
<span>C: </span>
<span data-counter="0">9999</span>
<br>
<span>D: </span>
<span data-counter="-1000">1000</span>
<br>
<span>E: </span>
<span data-counter="666">0</span>
<br>
</div>
</div>
I've been trying to add 1% to the width of the div using JS. I want to make it so that the bar's width increases in a smooth way ( I thought about using animations but it didn't work cause I need to specify conditions).
window.onload = function(){
for (let i = 0; i < 5; i++) {
const bar = document.querySelectorAll(".child-bar")[i];
for (let j = 0; j < 82; j++) {
//alert("j" + j);
console.log("bar width: "+ bar.style.width)
bar.style.width += '1%';
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="skill">
<label for="HTML">HTML</label>
<div class="parent-bar">
<span class="child-bar"></span>
<h4>82%</h4>
</div>
</div>
Maybe this example will help you?
window.onload = function() {
document.querySelectorAll(".parent-bar").forEach((el) => {
const barNode = el.querySelector(".child-bar");
const valueNode = el.querySelector("h4");
const max = 82;
const duration = 100;
let value = 0;
const tick = () => {
barNode.style.width = `${value}%`;
valueNode.innerHTML = `${value}%`;
if (value++ < max) setTimeout(tick, duration);
}
tick();
})
}
.child-bar {
display: block;
background: black;
height: 1rem;
width: 0;
transition: 0.1s 0s linear;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="skill">
<label for="HTML">HTML</label>
<div class="parent-bar">
<span class="child-bar"></span>
<h4></h4>
</div>
<div class="parent-bar">
<span class="child-bar"></span>
<h4></h4>
</div>
<div class="parent-bar">
<span class="child-bar"></span>
<h4></h4>
</div>
</div>
Here's a solution with verbose code and commentary for clarity, using setInterval.
(Note that span elements have display: inline by default, which is why setting their width has no effect.)
// Sets options and calls main function
const myOptions = {
MAX_WIDTH_PERCENT: 82,
FRAME_COUNT: 100,
FRAME_DURATION: 20
};
animateBars(myOptions);
// Defines main function
function animateBars(options){
const
// Destructures options object to make local variables
{ MAX_WIDTH_PERCENT, FRAME_COUNT, FRAME_DURATION } = options,
// Defines function to increment width
increment = (value) => value += MAX_WIDTH_PERCENT / FRAME_COUNT,
// Defines function to update bar (after incrementing width)
incrementAndupdateBar = (bar, oldWidth, timerId) => {
newWidth = Math.min(increment(oldWidth), MAX_WIDTH_PERCENT);
bar.style.width = newWidth + "%";
bar.nextElementSibling.textContent = Math.floor(newWidth) + "%"; // (For demo)
// Stops repeating the setInterval's function
if(newWidth == MAX_WIDTH_PERCENT){
clearInterval(timerId);
}
return newWidth; // Returns updated value
};
// Loops through bars
for(let bar of document.querySelectorAll(".child-bar")){
// Repeatedly updates current bar, keeping track of width as we go
let
width = 0, // Initializes width for the current bar
timerId; // ID for use by setInterval & clearInterval
timerId = setInterval( // (Returns an ID for later use)
// Takes 2 args: a func and a duration (in ms) to delay inbetween
function(){width = incrementAndupdateBar(bar, width, timerId);},
FRAME_DURATION
);
}
}
.parent-bar{ width: 300px; border: 1px dotted grey; }
/* spans ignore "width" by default; "inline-block" solves this */
.child-bar{ display: inline-block; height: 1em; background-color: lightgreen; }
h4{ margin: 0; text-align: center; }
<div class="parent-bar">
<span class="child-bar"></span>
<h4></h4>
</div>
I want to make two progress bars working on load. But the code which I write makes only one loading. Also those two progress bars has to be different in length when loaded. I don't want to repeat code, so I am adding arrays. But I am not quite sure that this is the best solution. Maybe in body tag it is possible to write two different functions, or only one can be onload? If it is possible with several functions onload, then the number array shouldnt't be used. My code below. Maybe anyone knows the solution?
<style>
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1, #myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body onload="move()">
<div class="myProgress">
<div id="myBar1"></div>
</div>
<div class="myProgress">
<div id="myBar2"></div>
</div>
<script>
function move() {
var ids = ["myBar1", "myBar2"];
var number = [60, 90]
var length = ids.length;
for(i = 1; i<=length; i++){
var elem = document.getElementById("myBar"+i);
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= number[i-1]) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
}
</script>
The problem was caused because you were mixing loops with async operations which usually doesn't turn out well. If you want to do that you should use let instead of var or do the operation in another function. Moreover you can set the width in the html element and read all the progress bars.
function move() {
for (var item of document.querySelectorAll(".myProgress")) {
loading(item.firstElementChild, +item.getAttribute("width") || 100); // replace 100 with default
}
}
function loading(bar, maxWidth) {
var width = 0;
var intervalId = setInterval(function() {
if (width >= maxWidth) clearInterval(intervalId);
else bar.style.width = ++width + '%';
}, 10);
}
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1,
#myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
<body onload="move()">
<div class="myProgress" width="60">
<div id="myBar1"></div>
</div>
<div class="myProgress" width="90">
<div id="myBar2"></div>
</div>
</body>
I'm trying to visualize a countdown via a div's width. This could be used for something like a banner system showing when the next banner will slide in, or for a notification system showing how long the notification will be visible.
So in my example below, I have the .outer div emptied after 5 seconds, but the .timer div's width is not reaching width: 0%; at the same time as the setTimeout() kicks in.
The variable len would represent how long the banner or notification would be shown for.
The calculation in the variable offset is what is throwing me off (I think), I cannot seem to get the calculation correct. I would like it to be dynamic, meaning, no matter what len is and what the width of the outer/parent div is, it will always take len time to reach width: 0%;.
I hope my explanation makes sense. Any help would be greatly appreciated.
const len = 5000;
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let timerWidth = timer.offsetWidth;
let offset = len / timerWidth;
let init = 100;
let interval = setInterval(() => {
init = init - offset;
timer.style.width = init + '%';
}, 1000);
setTimeout(() => {
outer.innerHTML = '';
clearInterval(interval);
}, len);
* {
box-sizing:border-box;
}
body {
padding: 100px 10px 10px;
}
.outer {
width: 100%;
border: 1px solid slategray;
padding: 10px;
}
.timer {
width: 100%;
height: 10px;
background: red;
transition: all 1000ms linear;
}
<div class="outer">
<div class="timer"></div>
<p>Some Message Here!</p>
</div>
Two problems with the code:
interval doesn't start as soon as the page is loaded so the CSS is late in transition.
offset was wrong indeed.
Here's how I fixed it:
let toElapse = 3000; // modify as you like
let tick = 1000; //if you modify this don't forget to replicate
//in CSS transition prop
let countDownEl = document.querySelector('#countdown');
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let init = 100;
// we calculate the offset based on the tick and time to elapse
let offset = init / (toElapse/tick);
countDownEl.innerHTML = init;
setTimeout(()=>{
// we need to start the first CSS transition ASAP so it is not late.
init = init - offset;
timer.style.width = init.toFixed(2) + '%';
},0)
let interval = setInterval(() => {
// the same interval.
countDownEl.innerHTML = init;
init = init - offset;
timer.style.width = init.toFixed(2) + '%';
}, tick);
setTimeout(() => {
// the same clearance timeout
outer.innerHTML = '';
clearInterval(interval);
}, toElapse);
* {
box-sizing:border-box;
}
body {
padding: 100px 10px 10px;
}
.outer {
width: 100%;
border: 1px solid slategray;
padding: 10px;
}
.timer {
width: 100%;
height: 10px;
background: red;
transition: width 1s linear;
}
<div class="outer">
<div class="timer"></div><span id="countdown"></span>
<p>Some Message Here!</p>
</div>
If you use percentage in width you don't need to know the width of your box.
you just need to substract and add on offset to timeout.
const len = 5000;
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let timerWidth = timer.offsetWidth;
let offset = 100 * 1000 / 5000;
let interval = setInterval(() => {
init = init - 20;
timer.style.width = init + '%';
}, 1000);
setTimeout(() => {
outer.innerHTML = '';
clearInterval(interval);
}, len + 1000);
Hey Guys so hoping to get some help on this, I have searched and searched all night and cannot find a simply way explaining how to implement these three features:
This is one of the effects i want - http://orteil.dashnet.org/cookieclicker/
When you click the cookie it pops up +1 and then fades away, If you apply upgrades it changes the number it displays and increments.
What's the best way to implement this? I have searched and searched and only come up with one or two jquery plugins which display popups when used, But there is not enough documentation or something explaining how to achieve the effect i want. also how to make it appear where my mouse is? I would even be happy if it just displayed in the middle of the image that i click.
Also is there a better way to store my number? At the moment my counter is a variable called "snowballs" and the display is a span which updates every second. is there a better way to store this number and display it? prefarably i would love to use a custom counter like this flipclockjs is this possible?
I have put all my code into a jsfiddle page but the image i click is a local file so it does not display. but at least so you can see my code i have provided the link.
http://jsfiddle.net/edznycyy/1/
Thanks so much for any help.
Code below
// Upgrades
var snowballs = 0;
var penguins = 0;
var penguinsps = 0.1;
var igloos = 0;
var igloosps = 0.5;
var eskimos = 0;
var eskimosps = 1.0;
var polarBears = 0;
var polarBearsps = 2.0;
// snowball functions to increase value
function snowClick(number){
snowballs = snowballs + number;
document.getElementById("snowballs").innerHTML = prettify(snowballs);
}
function userClick(number){
snowballs = snowballs + number;
document.getElementById("snowballs").innerHTML = prettify(snowballs);
}
//Buy functions
function buyPenguin(){
var penguinCost = Math.floor(10 * Math.pow(1.15,penguins)); //works out the cost of this cursor
if(snowballs >= penguinCost){ //checks that the player can afford the cursor
penguins = penguins + 1; //increases number of cursors
snowballs = snowballs - penguinCost; //removes the cookies spent
document.getElementById('penguins').innerHTML = penguins; //updates the number of cursors for the user
document.getElementById('snowballs').innerHTML = snowballs; //updates the number of cookies for the user
};
var nextCost = Math.floor(10 * Math.pow(1.15,penguins)); //works out the cost of the next cursor
document.getElementById('penguinCost').innerHTML = nextCost; //updates the cursor cost for the user
};
function buyPolarBear(){
var polarBearCost = Math.floor(200 * Math.pow(1.15,polarBears)); //works out the cost of this cursor
if(snowballs >= polarBearCost){ //checks that the player can afford the cursor
polarBears = polarBears + 1; //increases number of cursors
snowballs = snowballs - polarBearCost; //removes the cookies spent
document.getElementById('polarBears').innerHTML = polarBears; //updates the number of cursors for the user
document.getElementById('snowballs').innerHTML = snowballs; //updates the number of cookies for the user
};
var nextPolarBearCost = Math.floor(200 * Math.pow(1.15,polarBears)); //works out the cost of the next cursor
document.getElementById('polarBearCost').innerHTML = nextPolarBearCost; //updates the cursor cost for the user
};
function buyIgloos(){
var iglooCost = Math.floor(50 * Math.pow(1.15,igloos)); //works out the cost of this cursor
if(snowballs >= iglooCost){ //checks that the player can afford the cursor
igloos = igloos + 1; //increases number of cursors
snowballs = snowballs - iglooCost; //removes the cookies spent
document.getElementById('penguins').innerHTML = penguins; //updates the number of cursors for the user
document.getElementById('snowballs').innerHTML = snowballs; //updates the number of cookies for the user
document.getElementById('igloos').innerHTML = igloos;
};
var nextIglooCost = Math.floor(50 * Math.pow(1.15,igloos)); //works out the cost of the next cursor
document.getElementById('iglooCost').innerHTML = nextIglooCost; //updates the cursor cost for the user
};
function buyEskimo(){
var eskimoCost = Math.floor(100 * Math.pow(1.15,eskimos)); //works out the cost of this cursor
if(snowballs >= eskimoCost){ //checks that the player can afford the cursor
eskimos = eskimos + 1; //increases number of cursors
snowballs = snowballs - eskimoCost; //removes the cookies spent
document.getElementById('eskimos').innerHTML = eskimos; //updates the number of cursors for the user
document.getElementById('snowballs').innerHTML = snowballs; //updates the number of cookies for the user
};
var nextEskimoCost = Math.floor(100 * Math.pow(1.15,eskimos)); //works out the cost of the next cursor
document.getElementById('eskimoCost').innerHTML = nextEskimoCost; //updates the cursor cost for the user
};
//makes a number neater
function prettify(input){
var output = Math.round(input * 1000000)/1000000;
return output;
}
//Save Load and Delete Functions
function save(){
var save = {
snowballs: snowballs,
penguins: penguins,
igloos: igloos,
eskimos:eskimos,
polarBears:polarBears
}
localStorage.setItem("save",JSON.stringify(save));
};
function load(){
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.snowballs !== "undefined") snowballs = savegame.snowballs;
if (typeof savegame.penguins !== "undefined") penguins = savegame.penguins;
if (typeof savegame.igloos !== "undefined") igloos = savegame.igloos;
if (typeof savegame.polarBears !== "undefined") polarBears = savegame.polarBears;
if (typeof savegame.eskimos !== "undefined") eskimos = savegame.eskimos;
document.getElementById('penguins').innerHTML = penguins;
document.getElementById('snowballs').innerHTML = snowballs;
document.getElementById('igloos').innerHTML = igloos;
document.getElementById('polarBears').innerHTML = polarBears;
document.getElementById('eskimos').innerHTML = eskimos;
};
function deleteSave(){
localStorage.removeItem("save")
snowballs = 0;
penguins = 0;
igloos = 0;
eskimos = 0;
polarBears = 0;
document.getElementById('penguins').innerHTML = penguins;
document.getElementById('snowballs').innerHTML = snowballs;
document.getElementById('igloos').innerHTML = igloos;
document.getElementById('polarBears').innerHTML = polarBears;
document.getElementById('eskimos').innerHTML = eskimos;
}
function updateSPS(){
var sps = (penguins * penguinsps) + (polarBears * polarBearsps) + (eskimos * eskimosps) + (igloos * igloosps);
document.getElementById('SPS').innerHTML = prettify(sps);
}
function devGive(){
snowballs = snowballs + 100
document.getElementById("snowballs").innerHTML = prettify(snowballs);
}
window.setInterval(function(){
snowClick(penguins * penguinsps);
snowClick(polarBears * polarBearsps);
snowClick(eskimos * eskimosps);
snowClick(igloos * igloosps);
save();
}, 1000);
window.setInterval(function(){
updateSPS();
}, 100);
body {margin: 0px; }
body > div {
display: flex;
flex-flow:row wrap;
}
body > div > header,nav,main,prices, left,right,bottom, footer {
background: #7FE3F0; border-radius: 7px; margin: 5px; padding: 20px;
}
body > div > header { order: 1; height: 100px; flex: 0 1 100%;font: bold 30px Tahoma;text-align: center; }
body > div > nav { order: 2; height: 50px; flex: 0 1 100%; font: bold 30px Tahoma; text-align: center;}
body > div > prices { display: flex; flex-flow: column wrap; order:6; width: 200px; flex: 0 1 300px; }
#price {
width: 200px;
margin: 10px;
font: bold 15px Tahoma;
padding: 5px;
}
body > div > main {
order: 4;
text-align: center;
min-height:400px;
flex: 1;
}
body > div > right { display: flex; flex-flow:column wrap; order:5; width: 300px; flex: 0 1 300px; }
body > div > right > box1 > h1 { font: bold 20px Tahoma;}
body > div > right > box1,box2,box3,box4 { display: flex; max-width: 200px; max-height: 200px; border-radius: 7px; margin: 1px; padding: 5px; }
body > div > right > box1,box2,box3,box4 > span { display: flex; margin: 5px;}
body > div > right > box1,box2,box3,box4 > img { display: flex; max-width: 70px; max-height: 70px;}
body > div > left { order:3; width: 200px; flex: 0 1 600px; }
#snowball {
width: 350px;
height: 350px;
}
body > div > bottom {
order: 7;
height: 100px;
flex: 0 1 100%;
text-align: center;
font: bold 10px Tahoma;
}
body > div > bottom > img {
width: 50px;
height: 50px;
text-align: center;
}
body > div > footer {
order: 8;
height: 100px;
flex: 0 1 100%;
text-align: center;
font: bold 20px Tahmo;
}
<!doctype html>
<html>
<head>
<meta charset = "UTF-8">
<link rel="stylesheet" href="style1.css" />
<title> Winter Fun!</title>
</head>
<body>
<div>
<header>Winter Fun!</header>
<nav>
Snowballs: <span id="snowballs">0</span>
<br />
Snowballs Per Second: <span id="SPS" >0</span>
</nav>
<left>
</left>
<prices>
<box1 id = "price">Penguin Cost:<span id="penguinCost">10</span></box1>
<box2 id = "price">Igloo Cost:<span id="iglooCost">50</span></box2>
<box3 id = "price">Eskimo Cost:<span id="eskimoCost">100</span></box3>
<box4 id = "price">Polar Bear Cost:<span id ="polarBearCost">200</span></box4>
</prices>
<main >
<img title = "Click Me!" id="snowball" src="snowball.png" onclick="userClick(1)">
</main>
<right>
<box1>
<img id="penguins1" src="penguin.png" onclick="buyPenguin()">
<span id="penguins">0</span>
</box1>
<box2>
<img id="igloos1" src="igloo.png" onclick="buyIgloos()" >
<span id="igloos">0</span>
</box2>
<box3>
<img id="eskimos1" src="eskimo.png" onclick="buyEskimo()" >
<span id="eskimos">0</span>
</box3>
<box4>
<img id="polarBears1" src="polarBear2.png" onclick="buyPolarBear()" >
<span id="polarBears">0</span>
</box4>
</right>
<bottom>
<h1> Options!</h1>
<img id = "save1" src="save.png" onclick="save()">
<img id = "load1" src="load.png" onclick="load()">
<img id = "delete1" src="delete.png" onclick="deleteSave()">
</bottom>
<footer>
copyright MPWebDesign 2014
</footer>
</body>
<body onload = "load()">
<script type="text/javascript" src="main.js"></script>
<script src="jquery.js"></script>
<script type="text/javascript" src="snow.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
</html>
You can add the "popup" with jquery, position it under the mouse with css, and animate the element with jquery pretty easily. See the below commented code.
As for storing the data, localStorage is probably the quickest/easiest way.
Here is a working jsFiddle
Note that localStorage is just that, local. As in stored on the physical machine you are using. So if you were to visit this page on your laptop and do some stuff, then visit the page from your desktop, you would not see the changes you made using the laptop.
If users need to access the values from different devices, you'll need a backend (server side) solution like using php to connect to a mySql database to store and retrieve the information probly with a little ajax to keep everything asynchronous.
If you have this need and dont want to learn php , mySql, and ajax i'd recommend Parse which is basically a super easy to use backend storage API that you can interact with using just javascript. I use parse in several projects and would be lost without it.
EDIT: As for the placement of the code in the actual page
This page loads jQuery itself in the head tag, then loads the html, then loads the jQuery functions I wrote for you. This works because when the functions are called, jQuery has already been loaded and the elements we want to affect already exist on the page.
This page loads jQuery itself in the head tag, then loads the jQuery functions I wrote for you, then loads the html elements we want to affect. This does not work because when the functions are called, the elements we want to affect dont yet exist on the page.
This page loads jQuery itself in the head tag, then lists the jQuery functions I wrote for you, then loads the html elements we want to affect. This works because the functions are wraped in $(function(){ PUT CODE HERE }); which tells the page "hey page, I know Im putting this code up here at the top but, I want you to run the code inside it only after the page has fully loaded".
$( "#myClickDiv").click( function(event) {
// get current time in milliseconds since 1970/01/01 to use as a unique id for the popups
var id= new Date().getTime();
// use Ternary opperator to ask "does a value exist for `ownedPenguins` in local storage"
// if yes get that value, if no set val to 0
var val= localStorage.getItem("ownedPenguins") ? localStorage.getItem("ownedPenguins") : 0;
// create a div and add it to the main div
$( "#main").append('<div class="countDiv" id="'+id+'">'+val+'</div>');
// get the added div and set its position to that of the cursor
$("#"+id).css( {position:"absolute", top:event.pageY, left: event.pageX});
// annimate the added div
$("#"+id).animate({ "top": "-=100px","opacity": "0" }, "slow",function(){
$(this).remove();
}
);
// in the above
// "top": "-=100px" tells it to animate the div 100px up
// "opacity": "0" tells it to animate the div's opacity to 0
// "slow" is a shorthand speed setting
// function() {$(this).remove();} is a callback that will remove the element upon ompletion of the animation
});
// use `localStorage` to track how many of each thing a user has
$( "#myBtn").click( function(event) {
// use Ternary opperator to ask "does a value exist for `ownedPenguins` in local storage"
// if yes get that value, if no set val to 0
//get, increment, and set the value of `ownedPenguins` in `localStorage`
var val= localStorage.getItem("ownedPenguins") ? localStorage.getItem("ownedPenguins") : 0;
val++;
localStorage.setItem("ownedPenguins", val);
})
;