Execute conditional code onload() - javascript

I have two buttons on my page
<button id="reset" type="reset" value="Reset"
onClick="window.location.reload()"/>
<button id="random" type="button" onclick="randomPeg();">Empty random
peg</button>
function randomPeg()
{
window.location = window.location.href + "#refresh";
window.location.reload();
}
//At the start of JS code below
document.addEventListener("DOMContentLoaded", function(event) {
if(window.location.hash == "#refresh"){
window.location.hash="";
//Some more code
});
The first button just reloads the window.
On clicking the second button 'Empty random peg', I want to reload the page and then execute some more code after. I tried a few things with putting hash in the url but it doesn't seem to be working.

You could set a value into the persistent localStorage, and check at pageload if this value exists:
function reload(){
localStorage.setItem("showfancystuff",true);
window.location.reload();
}
//test on load
window.addEventListener("load",function(){
if(localStorage.getItem("showfancystuff")){
localStorage.removeItem("showfancystuff");
alert("wohoo weve reloaded!");
}
});

Related

Javascript pressing the button in an interval

I have a submit button, which sends the value with POST method to the same page.
<button id="log" class="btn bg-purple" formmethod=post value="2" name="start" formaction=start_server.php>Get Log</button>
When I press that button, I get the log from the file in a list using PHP.
What I want to do now is to make a script with javascript to automatically press the "Get Log" button to reload the log file every 2 seconds so I can have an interactive log, without pressing the button myself.
I have tried this script, but only the alert is working I guess, since it doesn't reload the log file at all.
<script type="text/javascript">
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
alert('test');
document.button["log"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 2000);
}
}
</script>
Replace your script with this:
$(document).ready(function(){
// this handles the click on yout "Get log" button
$("#log").click(function(){
//alert('test');
console.log("Click function");
$("#log").submit();
});
// This sets an interval to simulate a click every 2 seconds.
auto = setInterval(function(){
console.log("Interval iteration");
$("#log").click();
}, 2000);
});
Give an ID to your form and replace this line -
document.button["log"].submit();
With this -
document.getElementById('formID').submit();

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</button>

Checking for a button click

I want to redirect the page to a different location according to the button clicked, i want something similar to this:
if(document.getElementById('button').onclick == true)
{
//redirect page
}
However this code is not working for me:
document.getElementById('button').onclick = function() {
//redirect page
}​;​
the simplest way to do is add onclick() event in button tag.
<button id='button' onclick='redirectThePage();' >Click Me</button>
and in javascript
function redirectThePage(){
//redirect page
}
another way to do is
<button id='button'>Click me</button>
and in javascript
var button = document.getElementById('button');
button.onclick = function() { // redirect the page };
There are different ways to do the same thing.
1. addEventListener()
document.getElementById('button').addEventListener("click", function() {
redirect();
}​);​
function redirect(){
//redirect page
}
Pro
No nesting javascript and HTML
Contra
More code
Can't see in HTML code whats happens by click
2. onclick (answered by slashy)
Note: If you find this better, all owner goes him/her.
<button id="btn" onclick="redirect()">redirect</button>
<script>
function redirect() {
//redirect page
}
</script>
Pro
Less code
You can see in HTML code what there happens by a click event
Contra
Nesting HTML and Javascript.
It can be easily acheived also with javascript:
<button id="btn" onclick="redirect()">redirect</button>
<script>
function redirect()
{
window.location = "http://www.google.com/";
}
</script>
jQuery:
$('#button').click(function(){
window.location.href = "index.php";
});
HTML:
<button id="button">Click next</button>

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

Day/Night mode - CSS + JQuery - Cookies?

I'm testing javascript code for day/light background switch and I don't know how to do something. I'm newbie to javascript, so I'm learning new stuff.
So what I want to do?
When I click for example on button "Day" (which change background to yellow), I want that style for yellow background stay in the code after page is refreshed. I heard something about Cookies/LocalStorage, but I don't know how to implement it for this code.
Feel free to change whole code if you know easier way to do this, but please explain why it's better or why it should be like that.
Thanks in advance for your help.
Here is the code:
HTML:
<body id="body">
<input type="button" onclick="day();" value="Day" />
<input type="button" onclick="night();" value="Night" />
<input type="button" onclick="reset();" value="Reset" />
</body>
CSS:
.darkSwitch {
background: #808080;
}
.lightSwitch {
background: #ffff99;
}
JavaScript:
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function() {
var button = $('input[type=button]');
button.on('click', function() {
button.not(this).removeAttr('disabled');
$(this).attr('disabled', '');
});
});
Last edit: now disabling selected button on page load, CODE NOT IN THIS POST, see the latest JSFiddle
Explanation
What I did:
The code is put in between<script> tags at the end of the <body> (personnal preference)
I added the parameter event to the onClick event of the button element.
I added event.preventDefault() at the start of the onclick event of the button element: ensuring the page is NOT refreshed on the click of a button.
Warning: ALL the buttons will behave the same in your page. If you have other buttons, I suggest you add another class for those three buttons and bind the event on the button.myClass element.
I added a condition on the button state change, so the reset button won't get disabled.
eval($(this).val().toLowerCase()+"();"); gets the value of the the clicked button and executes the function attached to it.
Solution
HTML
<body id="body">
<input type="button" class="changeBg" onclick="day();" value="Day" />
<input type="button" class="changeBg" onclick="night();" value="Night" />
<input type="button" class="changeBg" onclick="reset();" value="Reset" />
</body>
JavaScript
(JSFiddle) <-- Check this out Updated with classes & cookies
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function () {
/* RegEx to grab the "bgColor" cookie */
var bgColor = document.cookie.replace(/(?:(?:^|.*;\s*)bgColor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var button = $('input[type=button].changeBg');
button.on('click', function (event) {
event.preventDefault();
/* Executing the function associated with the button */
eval($(this).val().toLowerCase() + "();");
button.not($(this)).removeAttr('disabled');
if ($(this).val() != "Reset") {
$(this).attr('disabled', '');
/* Here we create the cookie and set its value, does not happen if it's Reset which is fired. */
document.cookie = "bgColor="+$(this).val();
}
});
/* If the cookie is not empty on page load, execute the function of the same name */
if(bgColor.length > 0)
{
eval(bgColor.toLowerCase()+'()');
/* Disable the button associated with the function name */
$('button[value="'+bgColor+'"]').attr("disabled","disabled");
}
});
I recommend you don't use cookies unless localStorage is not supported. They slow your site down.
if(localStorage){
localStorage.setItem("bgColor", "lightSwitch");
}else{
document.cookie = "bgColor=lightSwitch";
}

Categories

Resources