the page keeps on reloading when i press the onclick button - javascript

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!)

Related

Using a button with HTML and JS in Markdown

I have this code in a markdown cell in Jupyter Notebook which I want to use to give the user a hint if they are struggling to solve a particular problem. The following code manages to create and display a clickable button, but when I click it, nothing happens. Any suggestions on what I can do so that when the button is pressed, the text inside my div tag will be revealed?
<button onclick="toggle_visibility('hidden-content')">Click to reveal hint</button>
<div id="hidden-content" style="display:none">
You can use len(my_list % 2 == 0 to check if the length of the list is even
</div>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The code may work in jsFiddle, that doesn't mean it will work in the OP's framework or that the script tag will be parsed by the markdown to HTML transpiler, which is probably reHype. What is most likely happening is the button tag is allowed to be parse but script tags are not.
The only solution to this is to somehow load an external script that creates an event listener to handle the click of your button. I've never used your framework so I have no idea how to accomplish this. Also, you should get in the habit of using event listeners rather than invoking a function via the onclick property.
Here's an example:
const button = document.querySelector('.some-button');
button.addEventListener('click', (event) => {
console.log(button.dataset.content);
alert(button.dataset.content);
});
<button class="some-button" type="button" data-content="hidden-content">Click Me</button>

How to toggle javascript buttons as off when page loads?

I'm trying to create a website that uses a hint button and a solution button to each of the problems it provides. I'm using a javascript function and a button that shows a new div when clicked, but it automatically shows the hint and solution as the page loads.
Is there a way I can set it so all buttons are automatically hidden? Or maybe can I get the function to run once as the page loads, I think that would work. Any ideas?
<button onclick="hint0()">Hint</button>
<div id="hint0">
Try reading the man pages for some of the listed commands on the OverTheWire level page. They may be useful!
</div>
<script>
function hint0() {
var x = document.getElementById("hint0");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Without seeing your code, it's a little difficult to give any feedback, but I can suggest a few things. You can use css to hide your hint and solutions - setting the display to none would be the easiest. The hints and solutions would be visible to anyone who viewed the page source or inspected the elements, if you only hide them. You could write an empty hint and solution container into your markup and then add the hint and solution text when the user interacts with the button. With Javascript or jQuery, on your click event, append the hint or solution to the DOM or set the innerHTML of the element.
Ok, I see your example code now - you can set a function to run on load and select your element by id and set it to display none. This page can help you understand the load event - https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
I think you mean to hide content of div not the buttons, just set your items to: style="display:none" inline.
function solution0() {
var x = document.getElementById("solution0");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function hint0() {
var x = document.getElementById("hint0");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="hint0()">Hint</button>
<div id="hint0" style="display:none">
Try reading the man pages for some of the listed commands on the OverTheWire level page. They may be useful!
</div>
<button onclick="solution0()">Solution</button>
<div id="solution0" style="display:none">
You need to use cat to print the contents of the file "readme". The file contains the password that you can copy and paste to log in to bandit1.
</div>
Use CSS in the header (not as a <link>, but actually inlined) to force those components hidden, then use JavaScript to show them later.
example:
.my-secret-div {
display:none;
}
...
<div class="my-secret-div"> the hint goes here </div>
...
Then use Javascript to remove the my-secret-div class.
Note that this doesn't hide the content from someone who could download the page or "inspect" the content using the browser developer tools.
Example fiddle: https://jsfiddle.net/5qnoghrf/

JQUERY: Why don't any of my alerts appear when either one of my conditions matches true?

My alert divs don't show up when I click the submit button.
An 'Error' div should alert when there's an empty required field and,
a 'Success' div should alert right before the form submits. The form submits so I know the validation check works but, I don't see any of my alert divs. See code below:
const goaForm = document.getElementById('goa-form');
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
let success = document.getElementById('success-msg');
let error = document.getElementById('error-msg');
let submitButton = document.getElementById("btnSubmit");
function checkForm() {
if (formCompleted) {
success.style.visibility = 'visible';
goaForm.submit();
} else if (formIncomplete) {
error.style.visibility = 'visible';
$("#error-msg").fadeOut(28000);
return false;
}
}
submitButton.addEventListener("click", checkForm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="error-msg" style="visibility: hidden;" class="alert alert-danger" role="alert">
<span class="fs-14">Error message div</span></div>
<div id="success-msg" style="visibility: hidden;" class="alert alert-success" role="alert">
<span class="fs-15">Success!</span></div>
// Submit Button
<button onclick="checkForm()" id="btnSubmit" class="btn btn-success lift d-flex align-items-
center" type="submit">Submit my application <i class="fe fe-arrow-right ml-5"></i>
</button>
Thanks for the help guys.
checkForm() is fired when your button is clicked, but it uses values (formCompleted, formIncomplete) defined earlier, on page load. So you may fill out your form, but those variables are not updated, and clicking the button uses the old values that were set when the page was first loaded.
Instead, check the input states and define those variables inside your checkForm() function, so that they are set up as the actual, current results when the button is clicked. Then the tests evaluate what the form looks like at the time of the button click.
function checkForm() {
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
// ... rest of your code ...
Update
Here's a working JSFiddle.
Notes:
You're using a mix of plain JS and jQuery. There's nothing technically wrong with that, but it would certainly be easier to read and maintain if you stuck to one. If you are going to take the hit in loading jQuery (extra http request, 90kb odd extra resource, etc) you may as well use it.
I am not sure if it is actually invalid, but the formCompleted test seems wrong. I'd use the standard !== '' instead of == !'' (I've done that in the JSFiddle);
If you're going to use the type comparison for formCompleted, you should be consistent and also use it for formIncomplete, ie use === '' (I've done that in the JSFiddle);
Don't use both an inline onClick() on the button, and add an addEventListener in your JS. They both do the same thing, use only one of them. It is considered bad practice to mix JS in with your HTML, so using the plain JS addEventListener (or jQuery .on()) is better. I've removed the inline one from the JSFiddle.

The onclick is not working on first click

I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit.
The HTML is here
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
And here is the JavaScript Function
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
The CSS I used is given
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
If you want to check this application live here is the link
Please click on this link to see app in running form
If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.
When the app is first loaded, both the toggleFahrenheit and toggleCelsius divs have no style attribute. They are getting display rules from the CSS, true, but they have no style on themselves.
So think about what your code sees, then. fahrenheit.style.display is null because that block doesn't have the style attribute yet. Therefore, fahrenheit.style.display === 'none' evaluates to false. As a result, the else block is executed and you end up displaying Celsius. Unfortunately, this is the default block which is shown, so the first click doesn't do anything.
The second click works because after the code executes once, now both div blocks have a style attribute.
To fix this, you should either put default style attributes onto the div tags or flip the logic in the code so you check on the Celsius block first, since that's the default display.
Personally, I would use classes to toggle display behaviour instead.
function toggle() {
var fahrenheit = document.getElementById("fahrenheit");
var celsius = document.getElementById("celsius");
fahrenheit.classList.toggle('hide');
celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
And yes, I use -40 degrees in the example because I'm lazy and I happen to know this is the same temperature in both systems (:
It does not work because this if (fahrenheit.style.display === 'none') will return NULL as there is no inline style on the element. this method won't "look" at CSS, it only works for inline styles. You could try this:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
to check the CSS properties in pure JS or you could use JQuery which would solve it in one line of code.
This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:
function yourFunction() {
document.addEventListener("DOMContentLoaded", function(){
// you works start here
});
}
The simple solution is to use the EventListener .
I had the same problem with the onclick but when using :
const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {
//Your code here
});
It works on first click!

How to change the value in an onClick with 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>

Categories