How to best define multiple variables? - javascript

First off I would like to say that I programmed a LONG time ago at school but I had alot of trouble getting into programming cause of ADD, so now I'm just 'trying' stuff at my own tempo with no pressure so I can pace it reall slow, but that does mean I'm a complete beginner, I know only snippets of some languages.
Now onto the problem, what I want to do eventually is change text color through a button click, so if I click a button with the label blue I want the text to turn blue and same with red etc.
So what I have is 2 buttons,
<button type="button" id="redButton" onclick="changeText()" value="red">Red</button>
<button type="button" id="blueButton" onclick="changeText()" value="blue">Blue</button>
Now in my javascript file I have the following:
var rButton = document.getElementById("redButton");
var bButton = document.getElementById("blueButton");
And I can alert both var with their value and it shows the value.
What I can't seem to figure is how to perhaps put rButton & bButton in a new var like
var cButton = [rButton, bButton];
Or something along those lines. Cause I can put cButton into an if statement right now and say this like:
if(cButton = document.getElementById("redButton"))
{
alert("Hello!");
}
else if(cButton = document.getElementById("blueButton"))
{
alert("Hello hello");
}
else
{
alert("Error!");
}
But that will only show Hello! and not Hello Hello even though I do press my blue button.
It's probably something realy stupid but I can't figure it out, and I haven't found much on google that I tried that worked.
Also yes changeText() is the function name which is where all this stuff is in.

If checking the colour is what you want to do, you can do it easily by simply passing the colour to the function as a parameter like this.
<button type="button" id="redButton" onclick="changeText('red')" value="red">Red</button>
<button type="button" id="blueButton" onclick="changeText('blue')" value="blue">Blue</button>
And then in in your javascript change your function to something like this.
function changeText(col){
if(col == "red")
{
alert("Hello!");
}
else if(col == "blue")
{
alert("Hello hello");
}
else
{
alert("Error!");
}
}
Also when you want to compare two values use == (comparison), when you use = (assignment) it will assign the value.

No need to get a reference to two different buttons. Instead, you can pass the color in the function call itself.
var textRef = document.getElementById("text");
function changeText(newColor){
console.log(textRef)
textRef.style.color = newColor;
}
<button type="button" onclick="changeText('red')" value="red">Red</button>
<button type="button" onclick="changeText('blue')" value="blue">Blue</button>
<p id="text">I am the text!!</p>

Try this
let cButton = document.querySelectorAll('.btn');
cButton.forEach(element => {
if (element.id === 'redButton') {
alert('Hello');
} else if (element.id === 'blueButton') {
alert('Hello Hello');
} else {
alert('Error');
}
})
Concerning what you said here
But that will only show Hello! and not Hello Hello even though I do press my blue button.
You can add an event listener like this :
cButton.forEach(element => {
element.addEventListener('click', (e) => {
if (e.target.id === 'redButton') {
alert('Hello');
} else if (e.target.id === 'blueButton') {
alert('Hello Hello');
} else {
alert('Error');
}
})
})
Note: That you have to add class="btn" in each button

Related

Can I check if a JavaScript function is called from a button's onclick attribute?

I have a JavaScript function that can be called either from a button click or from another function.
I am working on a simple game made with vanilla JavaScript and I have a function as below:
function end() {
// End the game
}
which can be called from a button click:
<input type="submit" id="endBtn" value="End Game" onclick="end()">
and can also be called from another JavaScript function:
function play() {
// Game logic
end();
}
The game can be ended by either the user clicking on the button or if certain conditions in the play() function are met.
Is it possible to know if the function is called from a button click?
As by default functions called from events are automatically passed an event value, you can check to see if the event value is not equal to undefined. Code example:
function yourFunction(event = undefined) {
if (event && typeof(event) == "object") {
alert("Called from element")
} else {
alert("Not called from element")
}
}
yourFunction()
<button onclick="yourFunction(event)">Click me!</button>
Yes, it's possible to assess whether it was called from a button click, see below:
btn = document.getElementById("btn");
testDiv = document.getElementById("testDiv");
btn.addEventListener("click", () => {
const payload = "called from button";
randomFn(payload);
});
function randomFn(getInput) {
testDiv.innerHTML = getInput;
}
<button id="btn">Click</button>
<div id="testDiv"></div>
Just let the function accept a string like "calledBy", like:
function myEvent(calledBy){
if(calledBy=="button") //It has been called by the button
else //It has been called by function
}
In your other function you pass "func" as parameter, while in the button you pass "button"
function secondFunction(){
//Do Stuff
myEvent("func");
}
In your button:
...onClick=myEvent('button')...
Hope to be clear, there might be other solutions, but this is the first thing that came in my mind.
One way to get this is by adding another parameter to the function that will allow you to differentiate the source. I.e. if you have a function
function abc(argument1) {
//logic
}
You could add
function abc(argument1, argument2){
if (argument2 === 'button' {
//some logic
}
//logic
}
If you call it from the button, you can call it with onClick: () => abc(argument1, 'button') so you know it came from the button. If called elsewhere, you would change the argument provide from 'button' to whatever you like.
the this in the element onclick will pass the element itself
so you can check if it's an element or not
function test(ele) {
if (ele instanceof Element) {
console.log("this is call by click button");
} else {
console.log("this is call by other way");
}
}
test();
<button onclick="test(this)">ckick me</button>
Actually there may be a workaround. Give your function a string parameter for ex $notifier.
When calling from button click give $notifier parameter as 'button' or whatever meaningful.
So from there by checking the parameter value you can get to know from where the function is fired.
function myFunction(notifier){
if (notifier=='button'){
// triggered from button
}
else if(notifier=='function'){
// triggered from function
}
}
and on button -> onclick="myFunction('button')"
I am not exactly sure what you are trying to do. However, if you truly must log/check if it was a button click or called from another function, you can do something like this:
function triggerFromFunction(d) {
triggerClick(true);
}
function triggerClick(comingFromFunction = false) {
document.getElementById("show").innerHTML = 'Coming from Function = ' + comingFromFunction;
}
<button onclick="triggerClick()">Trigger Click</button>
<button onclick="triggerFromFunction()">Trigger Function</button>
<p id="show"></p>
This solution is based on ES2015. Otherwise you can check if parameter is undefined in an if statement and proceed from there. Checkout:
https://www.w3schools.com/howto/howto_js_default_parameters.asp
All you need to do is look at the function parameters, specifically event.type, which all events will pass, if it has no params it must have been called directly (though you can pass a type if you wanted)
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", theFunction);
button.addEventListener("mouseover", theFunction);
button.addEventListener("mouseout", theFunction);
function theFunction(e) {
if (e && e.type) result.innerHTML = 'from ' + e.type
else result.innerHTML = 'has no type, perhaps theFunction()'
}
theFunction({type: 'foo'})
<button id="button">Click</button>
<div id="result"></div>

calling two js functions one after another using one button

Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.
function scrollWin() {
// First time click
if (e.name != 'Click') {
e.name = "Click";
function scrollWin() {
window.scrollBy(0, 85);
}
}
// When click it again..
else if (e.name == 'Click') {
e.name = "Unclick";
function myFunction() {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
}
<input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />
<p id="demo"></p>
You need to define one function which handles this action. It is probably best to store a variable where you can save the state of the clicking. Here is an example:
var clickCount = 0;
function scrollWin(button) {
// first click
if (clickCount === 0) {
window.scrollBy(0, 85);
}
// second or more click
else {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
button.style.display = 'none';
}
clickCount++;
}
<input type="button" onclick="scrollWin(this)" value="Click Me" />
<p id="demo"></p>
You need to get the fundamentals right. A function call will have its own scope and once the scope of a function ends, the variables are destroyed. I think you want to capture a second click for the element.
Don't try declaring a global variable for the same but try to set the elements property on first click which you can access on the second click. read that property on click and then manipulate.
I would suggest you to call the click event as
onclick="click123(this);"
and use this to set the property using setAttribute
I think this accomplishes what you described. You need to pass in the event of the button click and read the button text, but e.name probably wont work you'll need to use innerHTML or textContent. Then you can either perform the operations or call the functions you wish to execute depending on the button text which changes after the 2nd click.
function scrollWin(e) {
//First time click
if(e.textContent != 'Click'){
e.textContent = "Click";
window.scrollBy(0, 85);
}
else if(e.textContent == 'Click'){
e.textContent = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}//end else
}//end function
<button onclick="scrollWin(this)">Click</button>
<div id="demo"></div>
What I understand you want to perform two operation on same button but in two different condition, if you want to perform keep state and perform action according to that then. Like:
function scrollWin(e) {
var btn = e.target;
var state = btn.dataset.myattr;
if( state == 'state1'){
btn.dataset.myattr = 'state2';
e.name = "Click";
window.scrollBy(0, 85);
}else if (state == 'state2'){
btn.dataset.myattr = 'state1';
e.name = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
If you want to change the name attribute to something else you can do that and you don't have to change the JS code for that.

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}

Javascript yes/no/maybe ask function

I've started to learn programming using javascript. My aim is for the program to ask the user a set of yes/no questions. So far I've been using the prompt function for the asking but I wanted something less invasive, like a button. The problem is I can't get the program to wait for an answer to be picked without using a while loop, which freezes the program.
Is there a way to get the while loop to behave? If not what do I do?
Code( simplified, just function and buttons):
var currentAnswer = "unanswered"
function Change2Yes(){
currentAnswer = "y"
}
function Change2No(){
currentAnswer = "n"
}
function Change2Maybe(){
currentAnswer = "m"
}
function question(x){
document.write(x)
while (currentAnswer != "y" && currentAnswer != "n" && currentAnswer != "m"){
//do nothing THIS IS THE PART THAT FREEZES THE PROGRAM
}
if(currentAnswer == "y"){
answerlist.push("y");
latestAnswer="y";
}
else if(currentAnswer == "n"){
answerlist.push("n");
latestAnswer="n";
}
else if(currentAnswer== "m"){
answerlist.push("m");
latestAnswer="n";
}
currentAnswer= "unanswered"
}
<button id="btnYes" onclick="Change2Yes()">
Yes
</button>
<button id="btnNo" onclick="Change2No()">
No
</button>
<button id="btnMaybe" onclick="Change2Maybe()">
Maybe
</button>
Thanks so much :)
You should use events. Add a listener for clicks, for example:
var buttons = Array.prototype.slice.call(document.querySelectorAll('button'));
buttons.forEach(function (button) {
button.addEventListener('click', answer.bind(this, button.value));
});
function answer(currentAnswer) { ... };
The answer function will be called once a button is clicked.
http://jsfiddle.net/fWeq6/

Pure JS "If stament depending the number of click"

I was searching for this problem but I didn't find a solution. I'm trying to create a code where when you click a button do one thing, and when you press the same button later do other thing. I tried to create and "if-else" statement but I can't (don't know) how to count the number of clicks.
The code is:
<button type="submit" id="btnshwmap" onClick="init()" >Show Map</button>
And the if-else :
function init() {
var click =0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
Basically I'm trying to use this example Jquery if its the first time element is being clicked
But the answer are using Jquery I'm trying not use any library.
Thanks a lot!
The problem is that you keep on resetting click=0 every time you call the function.
I would suggest something like this:
function init() {
if( !init.click) {
// first, third, fifth etc.
init.click = 1;
]
else {
// second, fourth...
init.click = 0;
}
}
You just need to have the click counter outside the function, in the global area.
var click =0;
function init() {
if (click == 0) {
//do this once
click = 1;
} else {
//do this every other time
}
});//end click
You could try toggling the value set for the button with the click. Something like:
function init() {
var value = document.getElementById('btnshwmap').value;
if (value === 1) {
do this
document.getElementById('btnshwmap').value = 2;
} else {
do this
document.getElementById('btnshwmap').value = 1;
}
});//end click
Or keep a global variable to track the click status, rather than setting it every time you run the function.

Categories

Resources