activate javascript block of code - javascript

I have a Javascript block of code but I don't know how to activate it.
I would like it to be activated with a HTML button but I don't know if it's possible. I'm just beginning in coding =P
Here's the code:
var randomFlavour = Math.random() * 10;
if (randomFlavour < 1) {
var randomFlavour = "chocolate";
} else if (randomFlavour < 2) {
var randomFlavour = "vanilla";
} else if (randomFlavour < 3) {
var randomFlavour = "pistachio";
} else if (randomFlavour < 4) {
var randomFlavour = "strawberry";
} else if (randomFlavour < 5) {
var randomFlavour = "cotton candy";
} else if (randomFlavour < 6) {
var randomFlavour = "cookie dough";
} else if (randomFlavour < 7) {
var randomFlavour = "bubblegum";
} else if (randomFlavour < 8) {
var randomFlavour = "peanut butter";
} else if (randomFlavour < 9) {
var randomFlavour = "mint";
} else {
var randomFlavour = "gingerbread man";
}
console.log("Hello. I would like to have" + " " + randomFlavour + " " + "ice cream please.");

A cleaner way might be to do something like this:
flavors = [
'strawberry',
'apple'];
function getRandomFlavor()
{
random_index = Math.floor(Math.random() * flavors.length);
return flavors[random_index];
}
console.log(getRandomFlavor());
http://jsfiddle.net/Bm345/1/

To execute a function when a button is clicked, you first need a button:
HTML:
<button type="button">Click this button!</button>
Then you need to attach an event listener to the button. For beginners you will often be shown how to do this inline with an [onclick] attribute, but it's absolutely terrible practice and not a good habit to be in. If you were to add an event handler inline, you'd have to update all of them every time you wanted to do something as simple as change the event handler name. This is tedious and terrible for maintenance.
It's much easier long-term to bind events via JavaScript. You can do this a few different ways. The best is with addEventListener (or a library that makes use of addEventListener, such as with jQuery.fn.on):
JS:
//this line of code tells the `buttonVariable` element to call the
//`callbackFunction` when the button is clicked
buttonVariable.addEventListener('click', callbackFunction, false);
Another way is to use the onclick property:
buttonVariable.onclick = callbackFunction;
For that code to work, you need to have selected the <button> element, and created a callbackFunction function:
//declare the variable
var buttonVariable;
//declare the function
function callbackFunction () {
...do stuff...
}
//select the button
buttonVariable = document.querySelector('button');
//bind the function to the button for click events
buttonVariable.addEventListener('click', callbackFunction, false);
It's also important to note that the script must execute after the <button> has been added to the DOM. JavaScript scripts are executed synchronously:
<script>
var btn;
//this returns null because the script executes before
//the button element exists
btn = document.querySelector('button');
</script>
<button type="button">Click this button!</button>
<script>
var btn;
//this returns an HTMLButtonElement object
btn = document.querySelector('button');
</script>
Here's a working example on jsfiddle.

Wrap your js code in a function. Set the onclick listener of the button to call your function.
<html>
<head>
<script>
function myFunction() {
... all of your javascript code ...
}
</script>
</head>
<body>
<button onclick="myFunction()">My Button</button>
</body>
</html>

Related

Is there a way to check if a button has been clicked in HTML/Javascript? [duplicate]

This question already has answers here:
How to check if a button has been clicked using javascript?
(4 answers)
Closed 2 years ago.
I was wondering if there is a way of checking if a button has been clicked? This is the button I want to check:
<button id="money" onClick="myFunction()"> £25 </button>
I've looked all over to try and find a solution but any method I've tried just creates errors, this is one solution I've tried:
function myFunction{
if(document.getElementById('money').clicked == true){
alert("button was clicked")
}
}
Any help is greatly appreciated! Thanks
you can add class isClicked at the end of your function and after that each time you click it never work in your condition
function myFunction(){
const el = document.getElementById('money');
if (!Object.values(el.classList).some(function(x) {return x == 'isClicked'})) {
alert('your code');
}
el.classList.add('isClicked');
}
<button id="money" onClick="myFunction()"> £25 </button>
It should work when you remove the if(document.getElementById('money').clicked == true){ line and the corresponding curly brace, e.g.:
var clickedPreviously = false;
function myFunction() {
if (clickedPreviously) {
alert("button was clicked");
}
clickedPreviously = true;
}
To do this you can add the element a specific class name which is "alreadyClicked" in this snippet after that you can check the element has this class or not with the hasClass() function that I share below.
function myFunction() {
if(hasClass(document.getElementById('money'),'alreadyClicked')){
console.log("button was already clicked");
}
else {
console.log("First click, added to class: alreadyClicked to element");
document.getElementById('money').classList.add("alreadyClicked");
}
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button id="money" onClick="myFunction()"> £25 </button>
Another solution is using a new attribute with the same logic. You can add an attribute your element like data-clicked="false". According to Mozilla explained here;
Any attribute on any element whose attribute name starts with data- is
a data attribute. Say you have an article and you want to store some
extra information that doesn’t have any visual representation. Just
use data attributes for that.
<button
id="money"
data-clicked="true"
data-clicked-count="3">
£25</button>
To reach the data attributes with Javascript you can use below snippet.
var element = document.getElementById('money');
element.dataset.clicked; // true
element.dataset.clickedCount; // 3
And also you can set them more easily than class name updating and checking.
var element = document.getElementById('money');
element.dataset.clickedCount = 4
Full Solution with Data Attr
function myFunction() {
const myButton = document.querySelector('#money');
if(myButton.dataset.clicked == 'false'){
myButton.dataset.clicked = 'true';
console.log("data-clicked updated!");
}
myButton.dataset.clickedCount = parseInt(myButton.dataset.clickedCount)+1;
console.log("count of click : "+myButton.dataset.clickedCount);
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button
id="money"
onClick="myFunction()"
data-clicked='false'
data-clicked-count='0'>
£25
</button>
You don't need the if statement. You would just have to add an event listener on the button like this:
function myFunction() {
document.getElementById('money').addEventlistener('click', () => {
alert('button clicked')
}
Try like this
document.getElementById('money').onclick = function() {
alert("button was clicked");
};
document.getElementById('money').onclick = function() {
alert("button was clicked");
};
<button id="money"> £25 </button>

How can I fix my for loop in a javascript quiz?

I'm making a javascript quiz using a single HTML page. For some reason, my code will only display one question and upon clicking the element, it does not go to the next question. And it doesn't start the quiz with the first question.
I used a for loop inside a for loop. The first loop renders the question and then the other renders its corresponding choices. The questions and choices are held in an array containing the objects.
I've only been coding with Javascript and jQuery for a few weeks, so you'll have to tell me in beginner terms. I will have to refactor it. I apologize for it being somewhat messy.
I tried taking out the return commands. Same with preventDefault, no changes.
function renderQuiz(i) {
$heading.text("");
$mainDiv.text("");
$heading.text(quizQuestions[i].question);
for (var j = 0; j < quizQuestions[i].choices.length; j++) {
//console.log(quizQuestions[0].choices.length);
var li = document.createElement("li");
li.innerText = JSON.stringify(quizQuestions[i].choices[j]);
$mainDiv.append(li);
};
$('li').on("click", function() {
if (event.target.matches('li')) {
event.preventDefault();
var guess = event.target.innerText;
var answer = (JSON.stringify(quizQuestions[i].answer[0]));
if (guess === answer) {
timeLeft += 10;
console.log(timeLeft + "it works");
} else {
timeLeft -= 10;
console.log(timeLeft)
};
}
});
return;
};
mainPage();
$button.on("click", function(click) {
event.preventDefault();
for (var i = 0; i < quizQuestions.length; i++) {
renderQuiz(i);;
}
});
The $button click event is iterating through all of the questions, that is why the last question is the one displayed.
You need to define the variable i outside of the $button click function, then increment i on each click of the button.
var i = -1;
function renderQuiz(i) {
...
};
mainPage();
$button.on("click", function(click) {
event.preventDefault();
renderQuiz(++i);
});
There is an error in the $button onclick handler (in your console you should have "Uncaught ReferenceError: event is not defined").
If the function takes click as parameter then you should apply the method preventDefault() to that same parameter. In other words instead of
$button.on("click", function(click) {
event.preventDefault();
you should have
$button.on("click", function(event) {
event.preventDefault();
By the way there is the same error here
$('li').on("click", function() {
you should have
$('li').on("click", function(event) {
I hope this help.

How to Hide Element after number of clicks?

So I need to make an input tag hidden after it has been clicked at least twice. This is the JS/JQuery I have: (note I'm very new to the language)
var clickcounter = 0;
var clicker = document.getElementById("show-img-btn");
$("clicker").click(function(){
clickcounter = clickcounter + 1;
});
if (clickcounter >= 2) {("clicker").style.display = "none;"};
I really don't know the solution to this problem. It could be something as simple as not having enough equal signs or something complex as the whole thing being wrong. Please correct me!
I would use an Immediately Invoked Function Expression (IIFE) to keep the count variable safe from the rest of the scripts on the page.
You need to put all of your logic inside the click event handler, because the rest of the script only runs once.
You can simplify the check by using prefix incrementation of the count variable inside the conditional statement.
(function(count){
$("#show-img-btn").click(function(){
if(++count === 2) this.style.display = 'none';
return false; // returning false prevents form submission
});
})(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="show-img-btn" value="click me!">
You can simplify it even more if there is nothing else that needs to be done on the second click like so.
(function(count){
$("#show-img-btn").click(function(){
return ++count === 2 && (this.style.display = 'none'), false;
// increment & check; hide on second click; always return false
});
})(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="show-img-btn" value="click me!">
if (clickcounter >= 2) {("clicker").style.display = "none;"};
if (clickcounter >= 2) {alert("Hello! I am an alert box!!");};
Move this piece of code into the event handler. Otherwise, this is only ran once when your code is parsed, where clickcounter = 0;.
If you put it in $("clicker").click(function(){, it is run every time your event is triggered.
This should help you out,
<div id="clickMe">Click me!</div>
var counter = 0;
var clickMe = document.getElementById("clickMe");
clickMe.addEventListener("click", function () {
counter += 1;
if (counter == 5)
clickMe.style.display = "none";
console.log(counter);
});
You should adapt it to fit you. As you can see I checked the counter each time the div was clicked unlike yours which was once only.
Example
http://jsfiddle.net/xcgh99ut/
Edit 1
Also your code has an error in it.
$("clicker").click(function(){
}
According to your code clicker is variable so it should be,
$(clicker).click(function() {
}
Or using jQuery,
$("#show-img-btn").click(function () {
}
here is a working code: https://jsfiddle.net/xj1noced/
You have to put your condition into the onclick event - so it's run everytime the user clicked the element.
html:
<div id="clicker">
<div id="show-img-btn">Foo</div>
</div>
javascript:
var clickcounter = 0;
var clicker = document.getElementById("show-img-btn");
$("#clicker").click(function(){
clickcounter = clickcounter + 1;
if (clickcounter >= 2) {$("#clicker").css("display", "none")};
});

how to perform an if function when a button is pressed (javascript)

HTML
<button id="submit" onClick="">Finish questionnaire</button><br/>
Javascript
var submitButton = document.getElementById('submit');
var x = 0;
$(":radio").change(function() {
x = x + 1
if (x == 3) {
alert("Submitted")
} else {
alert("not submitted")
}
});
I am making a short questionnaire website. I would like to have submit button at the bottom of my page which will run the javascript code. This code will either give an alert of submit or not submitted. If the user has answered all the questions, then the alert will say submitted, otherwise, if a question is missed out, it will say not submitted. I have my javascript code, but I dont know how to implement it with a button. Please help
$("#submit").click( function() {
// whatever you want
});
Just wrap it in a .click(function(){CODE HERE})
You need eventListener for button click. A very simple Google search can give you the answer fast enough.
Still for your convenience, I'm writing the answer here for button click.
var submitButton = document.getElementById('submit');
var x = 0;
submitButton.addEventListener('click', function() {
x = x + 1
if (x == 3) {
alert("Submitted")
} else {
alert("not submitted")
}
});
Try this;
var x = 0;
$('#submit').click(function() {
x = x + 1
if (x == 3) {
alert("Submitted")
} else {
alert("not submitted")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit">Finish questionnaire</button><br/>

How do I use callback in javascript

I am adding following piece of javascript but I dont want to mess up the original intention of the onclick function (which is to add an item to sharepoint list).
<script type="text/javascript">
element.removeEventListener('click',redirect(),false)
function redirect()
{
var inputcCtrls = document.getElementsByTagName("input");
for(m=0; m<inputcCtrls.length; m++){
if(inputcCtrls[m].type == 'button' && inputcCtrls[m].value == 'Finish'){
window.parent.location = "http://intranet/surveys/Pages/ThankYou.aspx"; window.close();
}}}
</script>
From what i understand, you have one button you want to bind the function funcOnClick to.
You can add an ID to that button called redirect, then do something like this.
<script type="text/javascript">
window.onload = function(){
var button = document.getElementById('redirect');
button.onclick = funcOnClick;
}
</script>
<button id="redirect">Finish</button>
Update: Mmh. I forgot that the order in which the event handlers are executed is not guaranteed. Try this (redirect like below):
var inputcCtrls = document.getElementsByTagName("input");
for(m=0; m<inputcCtrls.length; m++){
if(inputcCtrls[m].type == 'button' && inputcCtrls[m].value == 'Finish'){
var input = inputcCtrls[m];
var __orig_handler = input.onclick;
input.onclick = function() {
__orig_handler();
redirect();
};
break;
}
}
Ok, maybe this is what you want:
function redirect() {
window.parent.location = "intranet/surveys/Pages/ThankYou.aspx";
}
var inputcCtrls = document.getElementsByTagName("input");
for(m=0; m<inputcCtrls.length; m++){
if(inputcCtrls[m].type == 'button' && inputcCtrls[m].value == 'Finish'){
inputcCtrls[m].addEventListener('click', redirect, false);
break;
}
}
Notice that you have to use attachEvent and onclick for IE.

Categories