getelementbyid().click not working - javascript

I am making a website that whenever I click and x is equal to a range of numbers, it plays audio, but after i click once when x is between those numbers, i will also play if x is not in the range. Please Help. Here is my code. by the way, i will not use jquery because it does not work on chrome.
if(x<=1200&&x>=600){
var n=true;
};
if(x<=1200&&x>=600&&n==true){
document.getElementById('a').onclick = function(){
audio.play();
n=false;
}
}
else{n=false}

What your code does is that it adds a click event listener on that element, and afterwards the click handler will trigger regardless of your x value because you don't have any checks inside the click handler.
The solution is to do create the click listener only once, and check for the value of x inside it. Something like this:
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
audio.play();
n = false;
}
}
See this (I've replaced audio playing with div highlighting, but it's the same principle):
var r = document.getElementById('r');
var n = true;
var x = 1000;
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
r.className = 'playing';
n = false;
printN();
setTimeout(function(){
r.className = '';
}, 2000);
}
}
function toggleN(){n = !n;printN()}
function printN(){document.getElementById('n').textContent = 'n is set to ' + n;}
function randomizeX(){x = Math.floor(Math.random() * 1200);printX()}
function printX(){document.getElementById('x').textContent = 'x equals ' + x;}
#r {display: inline-block; width: 50px; height: 50px; background: #ccc; transition: background 1s linear;}
#r.playing {background: green}
<button id="a">Hit me</button><br><br>
<div id="r"></div>
<p id="x">x equals 1000</p>
<p id="n">n is set to true</p>
<button onclick="toggleN()">Toggle n</button>
<button onclick="randomizeX()">Randomize x</button>

I'm not quite sure what you're trying to do but here a guest :
if(x<=1200&&x>=600){
var n=true;
var clicked = false;
};
if(x<=1200&&x>=600&&n==true || clicked==true){
document.getElementById('a').onclick = function(){
audio.play();
n=false;
clicked = true;
}
}
else{
n=false;
clicked = false;
}

This should do what you want, if i understood you correctly.
no reason to check x several times + check n, since n is only true if x is between your ranges.
var ab = document.getElementById('a');
var n = false;
if( x <= 1200 && x >= 600 ){
n = true; //If x is within range.
} else {
n = false; //Reset when x goes out of range.
}
ab.onclick = function(){
if(n){
audio.play();
}
}
Note: If a user clicks the button several times,
the audio plays several times.
This can be fixed by adding another variable checking if a user already clicked once,
Since i don't know your setup, i.e. should users be able to click to play the audio several times in a row(when it finish playing once), i can't supply you with a solution for that without knowing.

Related

How do you wait for a button to get pressed a certain amount of times before running another function?

I am trying to build a gambling simulator that lets you gamble with fake money to see if you'd win more often times than not. The game I am sort of trying to replicate is Mines from Roobet. In my game, there are 9 squares laid out in a grid like format. One of the squares is the bomb square, which means if you click it, you lose. The player does not know which square is the bomb square though. You have to click 4 squares, and if all of the ones you have clicked are non-bomb squares, then you win $50. If you click the bomb square, then you lose $50.
What I have been trying to figure out for like a week now is how do you make the game wait until either 4 non-bomb squares have been clicked, or 1 bomb square to have been clicked in order to do certain functions(subtract 50 from gambling amount, restart the game). I have tried while loops, but that crashes the browser. I have also tried if-else statements, but the code doesn't wait until either 4 non-bomb squares or 1 bomb square has been clicked. It just checks it instantly. So it results in it not working right. I also have tried for the function to call itself, and then check for either case, but it just results in an error saying "Maximum call stack size exceeded."
function bombClicked () {
for (let i = 0; i < array.length; i++) { //each square is put into an array named array
array[i].addEventListener("click", () => {
if (array[i].value == "bomb") {
array[i].style.background = "red";
redCounter++;
didLose = true
}
else{
array[i].style.background = "green";
greenCounter++;
didLose = false;
}
})
}
if (greenCounter >= 4 || redCounter >= 1) {
if (didLose == true) {
gamblingAmount.value = parseInt(gamblingAmount.value) - 50;
}
else {
gamblingAmount.value = parseInt(gamblingAmount.value) + 50;
}
reset();
}
}
What a fun little exercise! Here's my quick and dirty jquery solution.
const NO_OF_TRIES_ALLOWED = 4;
const SCORE_WON_LOST = 50;
var score = 0;
var tries = 0;
var bombId;
function restart() {
tries = 0;
$("button").removeClass("ok");
$("button").removeClass("bang");
bombId = Math.floor( Math.random() * 9);
$("#bombLabel").text(bombId);
}
function win() {
window.alert('you win!');
score += SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
function lose(){
window.alert('you lose!');
score -= SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
$(document).on("click", "button", function() {
if( !$(this).is(".bang") && !$(this).is(".ok") ) {
let buttonId = $(this).data("id");
if(buttonId === bombId) {
$(this).addClass('bang');
setTimeout(lose, 100); // bit of a delay before the alert
}
else {
$(this).addClass('ok');
tries++;
if(tries === NO_OF_TRIES_ALLOWED) {
setTimeout(win, 100); // bit of a delay before the alert
}
}
}
});
restart();
button{
width: 50px;
height: 50px;
padding: 0;
}
.ok{
background-color: green;
}
.bang{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id="0"></button>
<button data-id="1"></button>
<button data-id="2"></button><br>
<button data-id="3"></button>
<button data-id="4"></button>
<button data-id="5"></button><br>
<button data-id="6"></button>
<button data-id="7"></button>
<button data-id="8"></button><br>
Score: <span id="scoreLabel"></span>
It looks like you need some sort of state. I don't know what the rest of your code looks like, but maybe creating a helper to keep track of your counts might help:
class Counter {
constructor() {
this.count = 0;
}
inc() {
this.count ++;
}
getCount() {
return this.count
}
}
const counter = new Counter();
counter.inc();
counter.inc();
counter.inc();
counter.getCount(); // 3
Javascript should keep this in memory for you. I might have to see the rest of your code to understand how exactly to fix the issue, but maybe this will put you on the right track!

simple game using CSS, jQuery and HTML

I'm trying to make a game and still in the opening stages, I have the character and the code I thought would work, except when I run it nothing happens. I cant seem to find an error in it.
document.body.onkeydown = function(event){
var k = event.keyCode;
var chr = {
updown: function (){
var y = 0;
if (k==38) {
--y;
} else if (k == 40) {
++y;
}
return y;
},
leftright: function (){
var x = 0;
if (k == 37) {
--x;
} else if (k == 39) {
++x;
}
return x;
}
};
rogue.style.top = (chr.updown()) + "px";
rogue.style.left = (chr.leftright()) + "px";
}
#rogue {
position: relative;
top: 0px;
left: 0px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="jumpOPP.css">
<script src="jumpOPP.js"></script>
</head>
<body>
<img id="rogue" src="http://piq.codeus.net/static/media/userpics/piq_143310_400x400.png" >
</body>
</html>
I would appreciate any help at all.
Wrap your function like this:
document.body.onkeydown = function(event){
// Your event here
};
Take the handler off the body tag too.
JSFIDDLE
Change your function as below (its just a sample)
Suggested reading:
Retrieve the position (X,Y) of an HTML element
...
updown: function (){
var y = CURRENT_Y; // Get the current Y position of the image HERE
if (k==38) {
--y;
} else if (k == 40) {
++y;
}
return y;
},
leftright: function (){
var x = CURRENT_X; // Get the current X position of the image HERE
if (k == 37) {
--x;
} else if (k == 39) {
++x;
}
return x;
}
The logic you're using to set the top and left values is a little off. Note also that you need to parse the value to an integer so that you can add/remove from its value, and also provide a default.
Try this:
document.body.onkeydown = function(event){
var rogue = document.getElementById('rogue');
var currentY = parseInt(rogue.style.top || 0, 10);
var currentX = parseInt(rogue.style.left || 0, 10);
var speed = 3;
switch (event.keyCode) {
case 38: // up;
rogue.style.top = (currentY - speed) + 'px';
break;
case 40: // down;
rogue.style.top = (currentY + speed) + 'px';
break;
case 37: // left;
rogue.style.left = (currentX - speed) + 'px';
break;
case 39: // right;
rogue.style.left = (currentX + speed) + 'px';
break;
}
}
Example fiddle
Perfectly Working Answer: Run the Code Snippet and check
//bind an event when the user presses any key
window.onkeydown = function (e) {
if (!e) {
e = window.event;
}
//The event object will either be passed
//to the function, or available through
//window.event in some browsers.
var code = e.keyCode;
//that's the code of the key that was pressed.
//http://goo.gl/PsUij might be helpful for these.
//find our rouge image
var rouge = document.getElementById("rouge");
//get the image's current top and left position.
//rouge.style.top will find the top position out of our
//style attribute; parseInt will turn it from for example '10px'
//to '10'.
var top = parseInt (rouge.style.top, 10);
var left = parseInt (rouge.style.left, 10);
//We'll now compare the code that we found above with
//the code of the keys that we want. You can use a chart
//like the one in http://goo.gl/PsUij to find the right codes,
//or just press buttons and console.log it yourself.
if ( code == 37 ) { //LEFT
//time to actually move the image around. We will just modify
//its style.top and style.left accordingly. If the user has pressed the
//left button, we want our player to move closer to the beginning of the page,
//so we'll reduce the 'left' value (which of course is the distance from '0' left)
//by 10. You could use a different amount to make the image move less or more.
//we're also doing some very basic boundary check to prevent
//the image from getting out of the page.
if ( left > 0 ) {
rouge.style.left = left - 10 + 'px';
}
} else if ( code == 38 ) { //UP
//if we pressed the up button, move the image up.
if ( top > 0 ) {
rouge.style.top = top - 10 + 'px';
}
} else if ( code == 39 ) { //RIGHT
//move the image right. This time we're moving further away
//from the screen, so we need to 'increase' the 'left' value.
//the boundary check is also a little different, because we're
//trying to figure out if the rightmost end of the image
//will have gone
//further from our window width if we move it 10 pixels.
if ( left+rouge.width+10 < window.innerWidth ) {
rouge.style.left = left + 10 + 'px';
}
} else if ( code == 40 ) { //DOWN
if ( top+rouge.height+10 < window.innerHeight ) {
rouge.style.top = top + 10 +'px';
}
}
}
<img src="http://piq.codeus.net/static/media/userpics/piq_143310_400x400.png" id="rouge" style="position:absolute;top:0px;left:0px" />
Try this :
Create an array to hold key states : window.keyStates[];
Update the keyStates var with onkeyup / onkeydown events.
document.body.onkeydown = function (event) {
window.keyStates[event.keyCode] = true;
}
document.body.onkeyup = function (event) {
window.keyStates[event.keyCode] = false;
}
Create a loop to loop game :
var mainLoop = function () {
if (window.keyStates[38]) dostuff ();
if (window.keyStates[40]) dootherstuff ();
// etc....
}
window.setInterval(function() {mainLoop()}, 100);
The code is glitchy but you get the idea ? This way you can move your toon 2 directions at the same time too. Or manage virtually any key pressed at the same time.

Casino Roulette Game not working

http://csdev.cegep-heritage.qc.ca/students/cguigue/primordialCasino/game.html
supposed to click on the spin button and it should start the wheel spinning as well as changed the text on the screen in my displayArea, though when i click spin nothing happens,
getting undefined type error on the following code and not sure as to why
$('#wheel').rotate({
angle: 0,
animateTo: 2520,
duration: 4000
});
it says it isn't a function... :S
also...
if(currentGame.place == 0 && cellText == 0)
{
currentGame.setBet(betAmount * 40);
}
function rouletteGame(num, even, col)
{
this.place = num;
this.isEven = even;
this.colour = col;
this.win = 0;
this.hasBet = false;
this.setBet = function(bet)
{
this.win += bet;
this.hasBet = true;
}
says currentGame.place is undefined
but im initializing it in a for loop and its calling my above function...
for (var i = 1; i < rouletteWheel.length; ++i)
{
place = i;
if(i % 2 == 1)
{
isEven = false;
}
else
{
isEven = true;
}
if( i = red[count])
{
colour = "red";
++count;
}
else
{
colour = "black";
}
rouletteWheel[i] = new rouletteGame(place, isEven, colour);
}// for ()
.rotate() is not a built-in JQuery plugin. You will need to download or link the plugin in order for it to work. Add the following in your element of the HTML:
<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>
and see if that helps. with the first part of your problem.
As for the second part, I'm not sure if Javascript works this way too (I think it does), but you should create the new roulette game outside of the loop, and only change the values inside. Otherwise you are only creating a new roulette game for use within the scope of the for loop, not outside.
May want to check the documentation for this, as I'm not 100% positive about it. I just know it's how most other languages work.

How do I listen for triple clicks in JavaScript?

If this is for a double-click:
window.addEventListener("dblclick", function(event) { }, false);
How can I capture a triple-click? This is for a pinned tab in Google Chrome.
You need to write your own triple-click implementation because no native event exists to capture 3 clicks in a row. Fortunately, modern browsers have event.detail, which the MDN documentation describes as:
A count of consecutive clicks that happened in a short amount of time, incremented by one.
This means you can simply check the value of this property and see if it is 3:
window.addEventListener('click', function (evt) {
if (evt.detail === 3) {
alert('triple click!');
}
});
Working demo: http://jsfiddle.net/L6d0p4jo/
If you need support for IE 8, the best approach is to capture a double-click, followed by a triple-click — something like this, for example:
var timer, // timer required to reset
timeout = 200; // timer reset in ms
window.addEventListener("dblclick", function (evt) {
timer = setTimeout(function () {
timer = null;
}, timeout);
});
window.addEventListener("click", function (evt) {
if (timer) {
clearTimeout(timer);
timer = null;
executeTripleClickFunction();
}
});
Working demo: http://jsfiddle.net/YDFLV/
The reason for this is that old IE browsers will not fire two consecutive click events for a double click. Don't forget to use attachEvent in place of addEventListener for IE 8.
Since DOM Level 2 you could use mouse click handler and check the detail parameter of event which should be interpreted as:
The detail attribute inherited from UIEvent indicates the number of times a mouse button has been pressed and released over the same screen location during a user action. The attribute value is 1 when the user begins this action and increments by 1 for each full sequence of pressing and releasing. If the user moves the mouse between the mousedown and mouseup the value will be set to 0, indicating that no click is occurring.
So the value of detail === 3 will give you the triple-click event.
More information in specification at http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent.
Thanks to #Nayuki https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail - a DOM3 extension which is WIP https://w3c.github.io/uievents/
Here is the real Triple click event, which triggers only when all of three clicks fired with equal interval.
// Default settings
var minClickInterval = 100,
maxClickInterval = 500,
minPercentThird = 85.0,
maxPercentThird = 130.0;
// Runtime
var hasOne = false,
hasTwo = false,
time = [0, 0, 0],
diff = [0, 0];
$('#btn').on('click', function() {
var now = Date.now();
// Clear runtime after timeout fot the 2nd click
if (time[1] && now - time[1] >= maxClickInterval) {
clearRuntime();
}
// Clear runtime after timeout fot the 3rd click
if (time[0] && time[1] && now - time[0] >= maxClickInterval) {
clearRuntime();
}
// Catch the third click
if (hasTwo) {
time[2] = Date.now();
diff[1] = time[2] - time[1];
var deltaPercent = 100.0 * (diff[1] / diff[0]);
if (deltaPercent >= minPercentThird && deltaPercent <= maxPercentThird) {
alert("Triple Click!");
}
clearRuntime();
}
// Catch the first click
else if (!hasOne) {
hasOne = true;
time[0] = Date.now();
}
// Catch the second click
else if (hasOne) {
time[1] = Date.now();
diff[0] = time[1] - time[0];
(diff[0] >= minClickInterval && diff[0] <= maxClickInterval) ?
hasTwo = true : clearRuntime();
}
});
var clearRuntime = function() {
hasOne = false;
hasTwo = false;
time[0] = 0;
time[1] = 0;
time[2] = 0;
diff[0] = 0;
diff[1] = 0;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click button three times with equal interval
<button id="btn">Click me</button>
Also, I wrote jquery plugin TrplClick, which enables 'trplclick' event
it's very simple if you do it right, and you can even catch single, double, triple, ... clicks as you like. plain javascript, customizable click delay (timeout):
var clicks = 0;
var timer, timeout = 350;
var doubleClick = function(e) {
console.log('doubleClick');
}
var tripleClick = function(e) {
console.log('tripleClick');
}
// click timer
yourcontainer.addEventListener('click', function(e) {
clearTimeout(timer);
clicks++;
var evt = e;
timer = setTimeout(function() {
if(clicks==2) doubleClick(evt);
if(clicks==3) tripleClick(evt);
clicks = 0;
}, timeout);
});
pseudo-code:
var clicks = 0
onclick:
clicks++;
setTimer(resetClicksToZero);
if clicks == 3: tripleclickdetected(); clicks = 0;
I am working on a javascript code editor and I had to listen for triple click and here is the solution that will work for most browsers:
// Function to get mouse position
var getMousePosition = function (mouseEvent) {
var currentObject = container;
var currentLeft = 0;
var currentTop = 0;
do {
currentLeft += currentObject.offsetLeft;
currentTop += currentObject.offsetTop;
currentObject = currentObject.offsetParent;
} while (currentObject != document.body);
return {
x: mouseEvent.pageX - currentLeft,
y: mouseEvent.pageY - currentTop
}
}
// We will need a counter, the old position and a timer
var clickCounter = 0;
var clickPosition = {
x: null,
y: null
};
var clickTimer;
// The listener (container may be any HTML element)
container.addEventListener('click', function (event) {
// Get the current mouse position
var mousePosition = getMousePosition(event);
// Function to reset the data
var resetClick = function () {
clickCounter = 0;
var clickPosition = {
x: null,
y: null
};
}
// Function to wait for the next click
var conserveClick = function () {
clickPosition = mousePosition;
clearTimeout(clickTimer);
clickTimer = setTimeout(resetClick, 250);
}
// If position has not changed
if (clickCounter && clickPosition.x == mousePosition.x && clickPosition.y == mousePosition.y) {
clickCounter++;
if (clickCounter == 2) {
// Do something on double click
} else {
// Do something on triple click
resetClick();
}
conserveClick();
} else {
// Do something on single click
conserveClick();
}
});
Tested on Firefox 12, Google Chrome 19, Opera 11.64, Internet Explorer 9
This approach checks if the user has not changed cursor's position, you still can do something when you have single click or double click. Hope this solution will help everybody who will need to implement a triple click event listener :)
Configurable n-clicks event detector factory
const nClicks = (minClickStreak, maxClickInterval = 500, resetImmediately = true) => {
let timerId = 0
let clickCount = 0
let lastTarget = null
const reset = () => {
timerId = 0
clickCount = 0
lastTarget = null
}
return (originalEventHandler) => (e) => {
if (lastTarget == null || lastTarget == e.target) { // 2. unless we clicked same target
clickCount++ // 3. then increment click count
clearTimeout(timerId)
}
lastTarget = e.target
timerId = setTimeout(reset, maxClickInterval) // 1. reset state within set time
if (clickCount >= minClickStreak) {
originalEventHandler(e)
if (resetImmediately) {
clickCount = 0
}
}
}
}
Usage
table.addEventListener('click', nClicks(2)(e => { // double click
selectCell(e.target)
}))
table.addEventListener('click', nClicks(3)(e => { // triple click
selectRow(e.target)
}))

Trouble with onclick attribute for img when used in combination with setInterval

I am trying to make images that move around the screen that do something when they are clicked. I am using setInterval to call a function to move the images. Each image has the onclick attribute set. The problem is that the clicks are not registering.
If I take out the setInterval and just keep the images still, then the clicks do register.
My code is here (html, css, JavaScript): https://jsfiddle.net/contini/nLc404x7/4/
The JavaScript is copied here:
var smiley_screen_params = {
smiley_size : 100, // needs to agree with width/height from css file
num_smilies: 20
}
var smiley = {
top_position : 0,
left_position : 0,
jump_speed : 2,
h_direction : 1,
v_direction : 1,
intvl_speed : 10, // advance smiley every x milliseconds
id : "smiley"
}
function randomise_direction(s) {
var hd = parseInt(Math.random()*2);
var vd = parseInt(Math.random()*2);
if (hd === 0)
s.h_direction = -1;
if (vd === 0)
s.v_direction = -1;
}
function plotSmiley(sp /* sp = smiley params */) {
var existing_smiley = document.getElementById(sp.id);
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.setAttribute('onclick', "my_click_count()");
smiley_to_plot.style.position = 'absolute';
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
document.getElementById("smileybox").appendChild(smiley_to_plot);
}
function random_direction_change() {
var r = parseInt(Math.random()*200);
if (r===0)
return true;
else
return false;
}
function moveFace(sp_array /* sp_array = smiley params array */) {
var i;
var sp;
for (i=0; i < sp_array.length; ++i) {
// move ith element
sp = sp_array[i];
if (
(sp.h_direction > 0 && sp.left_position >= smiley_screen_params.width - smiley_screen_params.smiley_size) ||
(sp.h_direction < 0 && sp.left_position <= 0) ||
(random_direction_change())
) {
sp.h_direction = -sp.h_direction; // hit left/right, bounce off (or random direction change)
}
if (
(sp.v_direction > 0 && sp.top_position >= smiley_screen_params.height - smiley_screen_params.smiley_size) ||
(sp.v_direction < 0 && sp.top_position <= 0) ||
(random_direction_change())
) {
sp.v_direction = -sp.v_direction; // hit top/bottom, bounce off (or random direction change)
}
sp.top_position += sp.v_direction * sp.jump_speed;
sp.left_position += sp.h_direction * sp.jump_speed;
plotSmiley(sp);
}
}
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
function generateFaces() {
var smilies = new Array();
var s;
var i;
var css_smileybox=document.getElementById("smileybox");
var sb_style = getComputedStyle(css_smileybox, null);
// add info to the screen params
smiley_screen_params.width = parseInt(sb_style.width);
smiley_screen_params.height = parseInt(sb_style.height);
// create the smileys
for (i=0; i < smiley_screen_params.num_smilies; ++i) {
s = Object.create(smiley);
s.id = "smiley" + i;
s.top_position = parseInt(Math.random() * (smiley_screen_params.height - smiley_screen_params.smiley_size)),
s.left_position = parseInt(Math.random() * (smiley_screen_params.width - smiley_screen_params.smiley_size)),
randomise_direction(s);
smilies.push(s);
}
setInterval( function(){ moveFace(smilies) }, smiley.intvl_speed );
}
var click_count=0;
function my_click_count() {
++click_count;
document.getElementById("mg").innerHTML = "Number of clicks: " + click_count;
}
generateFaces();
The generateFaces() will generate parameters (for example, coordinates of where they are placed) for a bunch of smiley face images. The setInterval is within this function, and calls the moveFace function to make the smiley faces move at a fixed interval of time. moveFace computes the new coordinates of each smiley face image and then calls plotSmiley to plot each one on the screen in its new location (removing it from the old location). The plotSmiley sets the onclick attribute of each image to call a dummy function just to see if the clicks are registering.
Thanks in advance.
This is not a complete answer but it could give you some perspective to improve your code.
First of all, your idea of deleting the existing img so wrong. If it does exist, all you need is to just change its position so instead of this
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
you should do something like this:
if (existing_smiley !== null)
var smiley_to_plot = existing_smiley;
else {
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.style.position = 'absolute';
document.getElementById("smileybox").appendChild(smiley_to_plot);
smiley_to_plot.addEventListener('click', my_click_count);
}
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
As you can see new image is only being added if it's not already there. Also notice that adding events by using .setAttribute('onclick', "my_click_count()"); is not a good way to do. You should use .addEventListener('click', my_click_count); like I did.
Like I said this is not a complete answer but at least this way they response to the click events now.
FIDDLE UPDATE
Good luck!

Categories