How to change the value in an onClick with javascript? - javascript

I have a clicker game that I am developing and when I click the image at the start I have it set by default to be one click per click. I am wanting to make a button that forces the value of one click, to be two clicks per click. None of the solutions I have tried seem to work. Here is what I have:
HTML:
<img src="rust.jpg" id="click" value="Click" />
</div>
<script src="picture.js"></script>
<script src="clicks.js"></script>
<script src="2clicks.js"></script>
<p>Clicks: <a id="clicks">0</a></p>
<button onClick="twoClicks()">Click Me</button>
Clicks.js:
var clicks = 0;
function onClick(x) {
clicks += x;
document.getElementById("clicks").innerHTML = clicks;
};
2clicks.js:
function twoClicks() {
document.getElementById("onClick").innerHTML = onClick(2);
}
I want to click the button and make the img increase clicks by two

Since onClick already handles the DOM manipulation, just try
function twoClicks() {
onClick(2);
}

Might be making this to hard on your self
Why not have a click method and have it take an argument of it's multiplier.
For example if you need on click than do something like this
click(1)
and for two clicks do something like this click(2)
So for your game you could have code that looks like this in Javascript
function click(n){
for(var i = 0; i < n; i++){
addPoints()
}
}
Or even just add points directly through from your click function.
All you would have to do for the different clicks would call them as such
<button id="clickOne" onClick="click(1)">Click Me</button>
<button id="clickTwo" onClick="click(2)">Click me for two</button>
And if you want these values to increase with outside influence you could even have a value for your multiplier. There is allot of ways to approach this and if you need more assistance let me know in the comments.
If you need to make the clickOne element do two clicks suddenly something you can do is reassign the onclick attribute like so.
document.getElementById('clickOne').onclick = function(){click(2)};

u can do it by this way :
<button onClick="this.innerHtml = 'new value'">Click Me</button>

Related

the page keeps on reloading when i press the onclick button

i cant figure out how to stop the page reloading when i press the on click button... please if anyone can help tell me:)
(this is in html)
<button on click="My Function()">Try it</button>
<script>
function My Function() {
var x = document.get_Element_By_Id("mountain_bikes");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<script>
document.get_Element_)By_Id("mountain_bikes").style.display = "none";
i thought that this would show and hide when i toggle try it but it reloads the page every time i toggle please help!!
It looks like you've got a few errors going on here. Here's the answer:
// My Function() to myFunction()
function myFunction() {
// get_Element_By_Id to getElementById
var x = document.getElementById("mountain_bikes")
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
// get_Element_)By_Id to getElementById
document.getElementById("mountain_bikes").style.display = "none"
<!-- My Function() to myFunction() -->
<!-- on click to onclick —>
<!-- optionally add type="button" -->
<button type="button" onclick="myFunction()">Try it</button>
<!-- Added for demo -->
<div id="mountain_bikes">
My super cool mountain bikes.
</div>
As stated in a previous answer, it's just typos, but more than was mentioned. I'm sure you're still learning the basics, but this is something you should watch tutorials on, and maybe look at other people's code to get a better understanding of how JavaScript works. Your code works fine, without the typos, but this is something that's easily fixed by pasting the code into CodePen, or just running console.log() on your variables.
For future reference, you should also know about the preventDefault() function, that can be run on an event, like onClick. This is really only important in the case of forms, but if you run into other issues this may help. If you have a button in a form, but you don't want it to submit, make sure you include type="button" though. Here's how the preventDefault() function works:
// Setting constant variables since they never change.
// Using querySelector() for simplicity.
const article = document.querySelector('article'),
button = document.querySelector('button')
// Rather than using an onclick on the button in the HTML, I'm using an event listener to listen for the click event in JavaScript.
// This is the same thing as we had before, it just looks a little different.
button.addEventListener('click', (e) => { // Notice the e parameter. This is our event.
// This prevents the default behavior of our click event
e.preventDefault()
// This is the same as the if statement, just as a terny operator.
article.style.display === 'none'
?
article.style.display = 'block'
:
article.style.display = 'none'
})
// No need to set the style to none to start, since that's put in the HTML
<button type="submit">Click Me</button>
<!-- Here we set the display to none, so we don't have to do it in the JavaScript to start -->
<article style="display: none;">
<p>Without the preventDefault() function, the button would submit to the form—or at least try to, since there is no form—which would change the query in URL.</p>
<p>This could potentionally refresh the page, as is happening in your case.</p>
</article>
In your tag, the onclick needs to be one word, like this:
<button onclick="myFunction()">Try It</button>
Also, you shouldn't have spaces in your function names, I'm not a JS first guy, but I'm pretty sure no language allows for that (that I know of at least!)

Click a Button to Move through List of Webpages

I am creating a profile centered website.
I have a webpage that has fixed side buttons (SKIP and ADD). I know that I may need to create an array for all the webpages/profiles but... How do I start the process for the SKIP and ADD buttons to cycle to the NEXT profile in the list/array? Both the SKIP and ADD buttons move to the NEXT profile. However, a small notice appears when you click ADD to move forward.
I do have programming experience and have my AWS and Linux certifications. I'm not worried about following along! Please help. Any and all assistance is so greatly appreciated!!!
You weren't detailed enough in your question so that's the skeleton to handle a cursor for a list. A cursor that will be moved and processed by the add() and skip() functions called by the click events of the buttons Add and Skip. The div#currentItem holds the value of the current item in the list. Every time you press the Skip button, the cursor will move to the next item showing it's value on the div above said. Ever ytime you press the Add button, the function add() will be invoked:
<div id="currentItem">
</div>
<input type="button" onclick="skip();">Skip</button>
<input type="button" onclick="add();">Add</button>
<script>
var list = [];
var cursor = 0;
$(document).ready({
init();
});
function init(){
//feed here list var somehow
showCurrentItem();
}
function showCurrentItem(){
$('#currentItem').text( list[cursor] );
}
function skip(){
cursor++;
showCurrentItem();
}
function add(){
let currentItem = list[i];
//do something with currentItem
}
</script>

How to have JS take care of multiple events for a div

I'm drawing a blank on how to handle events within Javascript, and want to avoid using a modular function that has the "onclick" within the html tag. Basically, I want to write a function that will scroll to the section of the page containing that element on click, but I'm drawing a blank on how to do that.
I have a modular function like this:
var elmnt = $("#links").on("click", function() {
elmnt.scrollIntoView;
console.log;
});
Now, I pass the argument on the a href tag, but how do I have JS look for these events and scroll to them? Do I write a function for each link clicked? Is there a better way to do that? Thank you in advance.
Below are few corrections:
1) scrollIntoView is function
2) click callback handler should have reference to element
Check below code.
var elmnt = $("#links").on("click", function(ele) {
ele.scrollIntoView();
//console.log;
});
The idea is not for JS to "search for events", but to bind the buttons and destinations using a loop in an init script. Then all you need to do is to define the target of a button with an attribute, and JS will automatically take care of the rest.
Hence, you might wish to make scrollIntoView() a global function, and have it accept the element you wish to scroll to as a param, like such.
function scrollIntoView(target) {
// Scroll code here
}
For scroll code example see here and here
Edit: somethinghere pointed out that scrollIntoView() is actually natively supported, so there is no need to write your own function anymore.
Say you have 3 buttons and 3 destinations in your DOM (I will use button in place of a for clarity's sake):
<button class="button_type_a" type="button">Scroll to destination A</button>
<button class="button_type_a" type="button">Scroll to destination B</button>
<button class="button_type_k" type="button">Scroll to destination C</button>
...
<div id="dest_A">Destination A</div>
<div id="dest_B">Destination B</div>
<div id="dest_C">Destination C</div>
First prepare the buttons:
Add an arbitrary class (goto_button) to indicate the intended action of the button
Add an arbitrary attribute (target) to indicate their respective destinations
Something like this:
<button class="button_type_a goto_button" type="button" target="dest_A">Scroll to destination A</button>
<button class="button_type_a goto_button" type="button" target="dest_B">Scroll to destination B</button>
<button class="button_type_k goto_button" type="button" target="dest_C">Scroll to destination C</button>
in which the value of target is the id of the destination.
Then in your JS, first find all your buttons:
var gotoButtons = document.getElementsByClassName("goto_button");
Then loop through your buttons, and for each one search and bind to their destination:
for (let btn of gotoButtons) {
let target = btn.getAttribute("target");
let destination = document.getElementById(target);
btn.addEventListener("click", () => {
destination.scrollIntoView();
});
}
Load this JS as an init script for your page and you should be all set.

HTML multiple onclick events not occurring when I want

When the user clicks read more, I want the page to change to the new page (News.html) and then scroll down a specific amount so that it lines up with the article, but what's happening is that when you click read more, the page lowers a specific amount and then changes to the top of the news.html page
<article>
<h3>Is Joe Hart right for Torino?</h3>
<img src = "News_Images/Joe_Hart_Torino.jpg" alt = "Joe" width="225" height="150">
<button class = "btn btn-block btn-primary" onclick ="Change(); scrollWin();">
<p>Read</p>
</button>
</article>
<script>
function Change(){
document.location.href = "News.html";
}
</script>
<script>
function scrollWin() {
window.scrollBy(100, 175);
}
</script>
You can use fragment for instance #content. Put in appropriate place on the
News.html page and update your function to something like
function Change(){
document.location.href = "News.html#content";
}
Btw when you click only one onclick event occurs it's not supposed to occur multiple events and in your case both functions are executed, just moving takes time and you see scrolling first. Using scroll with hardcoded value is not good idea, you'll need to update it every time you update content of News.html
**UPDATE**
procrastinator is right, see comment below, just use anchor if it's applicable for you.
When you move to another page, javascript reloads and does not continue execution from where you left off.
A solution to your problem could be using a request parameter.
Change your function to this:
function Change(){
document.location.href = "News.html?scroll=yes";
}
And in your News.html page, add this code to the page's onload event:
var url = new URL(window.location.href);
var param = url.searchParams.get("scroll");
if (param == "yes")
window.scrollBy(100, 175);

JS Button - random font

<div id="fontfamily">test
</div>
<button onclick="myFunction()">Try it</button>
var fontType = [ "Arial", "Verdana", "Courier"];
var num;
num=Math.floor(Math.random()*3);
document.getElementById("fontfamily").style.fontFamily =fontType[num];
console.log(num);
function myFunction() {
var x = document.getElementById("fontfamily").name;
document.getElementById('myFunction()').innerHTML = x;
}
i dont know what not working. my goal is that in every time that i press the button the font change.
tnx!
There are many things wrong in your code, so let's review them one at a time.
First, onclick="myFunction()" runs myFunction when you click on the button, but it doesn't run the lines which aren't in the function. Your randomization code is before the function, so it is executed once, when the page loads.
Depending on where you put that code (such as in a script tag in the head), the page might not have loaded. This means the document.getElementById function will fail because the elements haven't loaded yet. That might be another reason why it's not working.
var x = document.getElementById("fontfamily").name;
document.getElementById('myFunction()').innerHTML = x;
This tries to get the name attribute of the div. There's no name attribute on that div, so it will fail. Next you're trying to get an element where the id is equal to myFunction(). That doesn't make any sense. myFunction() isn't an id on an element. I don't know what you were trying, so I just got rid of most of the useless code.
Here's the solution, simply done by moving the needed code inside the function.
var fontType = ["Arial", "Verdana", "Courier"];
function myFunction(e) {
document.getElementById("fontfamily").style.fontFamily = fontType[Math.floor(Math.random() * fontType.length)];
}
<div id="fontfamily">test</div>
<button onclick="myFunction(event)">Try it</button>

Categories