How to count clicks of random images? - javascript

I'm trying to make a random sequence triggered by mouse click, and track how many times a user would click on the images. Could anyone help me with that? Thanks!
Below are my code that are pulling images randomly:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
function changePic()
{
var num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
document.getElementById("p").value++;
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="changePic()" /></p>
</div>
</body>

Assume you start your image sequence from 1, you can use a counter to count your image click times.
When image element is clicked, buttonclick function will track how many times user has clicked on the image. And then change your current image sequence number which will show a different image.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
const counter = {};
let num = 1;
function changePic()
{
num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
counter[num] = (counter[num] || 0) + 1;
console.log(counter)
//if you want to show current count for the sequence, you can use console.log(counter[num])
changePic()
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="buttonclick()" /></p>
</div>
</body>

try make clickCounter object with a key equal to the picture number and better use onclickmethod in JS but not in html
let num = 1;
const clickCounter = {};
const randomPic = document.getElementById('randomPic')
randomPic.onclick = function(){
clickCounter[num] = (clickCounter[num] || 0) + 1;
changePic();
console.log(clickCounter); // if you need
}
function changePic() {
num = Math.ceil(Math.random()*9);
randomPic.src = num + ".jpg";
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "randomPic" width="400px" height="600px"/></p>
</body>
</html>

Related

Why is document.getElementById() not working?

I want to make a program which adds a textbox every time you click a button. Here's my code:
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="linelist"></div><br />
<button id="addline" onclick="Addline();">+</button>
</body>
</html>
When I run it, it generates an error. Why is this occurring?
You have to define linelist outside the functions first with let or var:
let linelist = null;
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button
class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}

Javascript hit counter

I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}

switch from image to random image onclick with JavaScript

I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>

Is possible search an element array from input?

I'm creating a little script to try and search for an element in the array based on input.
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
if(modulo.indexOf(link) > -1) {
alert("Your site is:" + modulo);
}
else {
alert("Sorry, I don't found:" + modulo)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
</body>
</html>
Anyone can explain to me how to do that (if there's another way to do it better, inform me), and why my code doesn't run? Thanks!
Code explanation: I've used var modulo to contain the value of the input. Then I've created a variable to contain the link. Then if-else statement and indexOf to search and find it.
Thanks, the code solution is: https://plnkr.co/edit/bDt4n34KBFAvZrSWmb4a?p=preview
You can try with this plunker https://plnkr.co/edit/bDt4n34KBFAvZrSWmb4a?p=preview it used event trigger to have a button to search website :
<button onclick="myFunction()">Search</button>
and I wrote your code into a function.
I hope this will help you
The final state :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<input type="text" id="modulo" class="form">
<button onclick="myFunction()">Search</button>
</body>
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
function myFunction() {
var input = document.getElementById("modulo");
var results = [];
for(var i = 0; i < link.length; i++) {
if(link[i].indexOf(input.value) > -1) {
results.push(link[i]);
}
}
if(results.length == 1) {
alert("Your site is:" + results[0]);
}
else if (results.length > 1){
alert("Sorry, your search return more than one result:" + results)
}
else {
alert("Sorry, I don't found:" + input.value)
}
}
You have
if(modulo.indexOf(link) > -1)
but I think that it should be
if(link.indexOf(modulo) > -1)
Assuming that modulo is a single string element, this will search the link array for that element and return the index of that element.
I think you were on the right track. You just need a few things:
a button to initiate the search
put your code in a function so you can call it
you want to search the array link for the value of the input modulo
function findIt() {
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
if (link.indexOf(modulo) > -1) {
alert("Your site is:" + modulo);
} else {
alert("Sorry, I don't found:" + modulo)
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
<input type="button" onclick="findIt()" value="find it">
</body>
</html>
function runscript() {
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
var found = false;
for(var i = 0; i < link.length; i++) {
if (link[i].indexOf(modulo) > -1) {
alert("Your site is:" + link[i]);
found = true;
}
}
if (!found) {
alert("Sorry, I don't found:" + modulo)
}
}
And the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
<input type="button" onclick="runscript()" value="search" />
</body>
</html>
You will need to press button for search

Creating paragraphs based on user input

I'm having trouble, grabbing the user input, and having the onclick operator create additional paragraphs with each click.
Here is my HTML code.
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script src="../js/addPara.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>
Here is Javascript code:
window.onload = function() {
document.getElementById("addheading").onclick = pCreate;
};
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = par;
var area = document.getElementById("par");
area.appendChild(userPar);
}
userPar.innerHTML = par;
should be
userPar.innerHTML = parNew;
In your code:
> window.onload = function() {
> document.getElementById("addheading").onclick = pCreate;
> };
Where it is possible (perhaps likely) that an element doesn't exist, best to check before calling methods:
var addButton = document.getElementById("addheading");
if (addButton) {
addButton.onclick = pCreate;
}
Also, there is no element with id "addheading", there is a button with id "heading" though.
> function pCreate() {
> var userPar= document.createElement("p");
> var parNew = document.getElementById('userParagraph').value;
> userPar.innerHTML = par;
I think you mean:
userPar.innerHTML = parNew;
if you don't want users inserting random HTML into your page (perhaps you do), you can treat the input as text:
userPar.appendChild(document.createTextNode(parNew));
.
> var area = document.getElementById("par");
> area.appendChild(userPar);
> }
Your variable names and element ids don't make a lot of sense, you might wish to name them after the data or function they represent.
I did it and it worked.
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script>
window.onload = function() {
document.getElementById("heading").onclick = pCreate;
}
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = parNew;
var area = document.getElementById("par");
area.appendChild(userPar);
}
</script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>```

Categories

Resources