Is there a way to add a function to my current button? - javascript

I am using JS and HTML. I have a button that displays the next section of html, but I wanted to add an additional function.
// Display Thanks Message
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById("btn").addEventListener("click", addPerson function() {
q5.style.display = "none";
end.style.display = "block";}
});
In this addPerson is the function I am trying to include. In this current code I keep getting syntax errors.

Call addPerson() inside the function.
// Display Thanks Message
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("btn").addEventListener("click", function() {
addPerson();
q5.style.display = "none";
end.style.display = "block";
}
});
});

Related

Getting my last clicked buton to store in local storage

I am creating an google chrome extension and I'm trying to create a start/ stop button. For some reason when I click the stop button, it will go to the start button while on the popup but when I exit off the popup, it resets back to the other button
Im trying to get my last clicked button to store in local storage so that when i click off the extension popup it will still show the button that was opposite of last clicked. For some reason when my stop button is clicked, it doesn't seem to store the variable lastclicked in local storage
Do anyone know what the issue may be or how to resolve this?
//Start and Stop buttons for logging
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//attempt to get start/stop logging buttons to work--underwork
function Logger(isLogging) {
let logger =''
if (isLogging){
btnStart.style.display= "none";
btnStop.style.display= "block";
logger = 'logging'
addRow();
} else {
btnStart.style.display= "block";
btnStop.style.display= "none";
logger = 'not logging'
}
//using storage API to save data for last btn pressed--underwork
chrome.storage.local.set({key: logger}, function() {
console.log('value is set to ' + logger);
});
}
var lastClicked = btnStart;
//button to start/stop logging
document.addEventListener("DOMContentLoaded", function () {
//get lastClicked first to make decisons
chrome.storage.local.get({'lastClicked': lastClicked}, function(result) {
if (result = btnStart) {
//works
btnStart.style.display= "none";
btnStop.style.display= "block";
console.log("last clicked is start button");
addRow();
} else if (result = btnStop) {
//not working
btnStart.style.display= "block";
btnStop.style.display= "none";
console.log("last clicked is stop button");
} else {
console.log("else statement");
}
//works
btnStart.addEventListener("click", function() {
Logger(true);
chrome.storage.local.set({'lastClicked': lastClicked}, function() {
lastClicked = btnStart; //doesnt know if it saves
console.log('logging started successful');
});
});
//works
btnStop.addEventListener("click", function() {
Logger(false);
chrome.storage.local.set({'lastClicked': lastClicked}, function() {
lastClicked = btnStop; // doesnt know if it saves
console.log('logging stopped successful');
});
});
});
chrome.storage.local.get(['key'], function(result) {
console.log('value currently is ' + result.key);
});
First, try to fix if (result = btnStart), you assign btnStart to result and it's always true if btnStart exists.
Change with if (result === btnStart) or if (result == btnStart)
Same thing for (result = btnStop)
Edition
I've spent some time to understand what you try to achieve and by reading the storage doc for extensions.
I think this code is really more readable
document.addEventListener("DOMContentLoaded", function () {
//Don't care about which button is used, keep the logica idea... is it started?
let started = true;
//Wait for content loaded before getting element is a better idea.
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//Keep all the logic together
const setStarted = s => {
started = s;
//This is a asynchronous call, I putted everything on the callback but as you want
chrome.storage.local.set({started: started}, () => {
console.debug("Storing `started` to storage with value:", isStarted);
btnStart.style.display = started? "none" : "block";
btnStop.style.display = !started? "block" : "none";
if ( started ) {
//What's that?
addRow();
}
});
};
//Get seems to by used with a string key, not an object
chrome.storage.local.get(['started'], (result) => {
console.debug("Reading `started` from storage gives", result.started);
//Using setStarted avoid repeting always the same thing
setStarted(result.started);
});
btnStart.addEventListener("click", () => setStarted(true) );
btnStop.addEventListener("click", () => setStarted(false) );
});

setTimeout() starts onload instead of onclick. How do I get it to start only after I click it?

I am trying to have the setTimeout() function start only after I click a button as opposed to when the page loads. Here is my code:
function convert() {
'use strict';
var utcDate = new Date();
var message;
var output = document.getElementById('output2');
message = 'today is ' + utcDate.toUTCString();
if (output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}
document.getElementById('output2').value = message;
}
button.onclick = setTimeout(convert, 5000);
If you want to start on click of the button. Than you this should be the way:
button.onclick = function() { setTimeout(convert, 5000); }
change
button.onclick = setTimeout(convert, 5000);
to
button.onclick = function () { setTimeout(convert, 5000);}
or you could use jQuery if you are already loading the library for something else
$('#idOfButton').click(function () { setTimeout(convert, 5000);}); //more efficient than $.on()
or another way using jQuery
$('#idOfButton').on('click', function () { setTimeout(convert, 5000); });
As with many tasks in programming, there are many ways to accomplish your task
button.onclick = function(){setTimeout(convert, 5000);}
You need to put the setTimeout part in a function. So that last line would look like
button.onclick = function(){setTimeout(convert,5000)}

toggle() not working for content loaded with ajax?

$('.slideArrow').toggle(function (event) {
//some code
}, function (event) {
//some code
});
This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.
What should I do?
In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?
$('.common-parent').on('click','.target-of-click',function(){
//some code
})
The flag method :
var flag = false;
$(document).on('click', '.slideArrow', function(event) {
if (flag) {
// do one thing
}else{
// do another thing
}
flag = !flag;
});
the data method
$(document).on('click', '.slideArrow', function(event) {
if ( $(this).data('flag') ) {
// do one thing
}else{
// do another thing
}
$(this).data('flag', !$(this).data('flag'));
});

add1 does not exist in DOM How to Add?

I am having an issue with java-script and an HTML form.
I have a form and next to the form is a button called "add" when I click add the second form appears. Next to form 2 is another button called add1, when I click this button I am wanting the third form to display. For some reason only the first add button is working.
Below is the code I have so far:
<style type="text/css">
#newservicesetup1, #newservicesetup2 {
display:none;
}
</style>
<script type="text/javascript">
function showform(theform) {
var showHides = new Array('newservicesetup1','newservicesetup2');
for (i=0;i<showHides.length;i++) {
document.getElementById(showHides[i]).style.display=
(document.getElementById(showHides[i]).id == theform) ? 'block' : 'none';
}
}
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); }
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); }
}
}
window.onload = loadBehaviors;
</script>
Try adding a semicolon to the end of the assignments:
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); };
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); };
}
}
You can check your Javascript for syntax using Online Javascript Lint.
why not just
document.getElementById('add').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
document.getElementById('add1').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
that will show the correct forms when you click the appropriate button. if you want them to disappear when clicking again, you will only need a slight modification
When loadBehaviors() is called, add1 does not exist in the DOM yet. Bind to the event handler after you add it to the DOM.

Page resets after javascript function finishes

I'm doing a simple html page for a project.
I have a submission form.I use jquery to validate it (no sure if i'm doing ir right).
After the submission is validated,i want to save the user's details(name,password),in an array. The array is created when the script loads.
I added the function SubmitUser() to the onclick event,but when the function finishes,and adds the user,the page resets,and the variables are reset.
I wonder if someone could point out to me what i'm doing wrong.
Thanks in advance,
Boris
Here's the script code:
var userArray = new Array();
var passArray = new Array();
var userNumber = 0;
//Adding rules for validation
$(document).ready(function(){
$("#registerForm").validate({
rules: {
password: {
required: true,
minlength: 8
}
}
});
});
//Add a method to validate
$(document).ready(function(){
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-zA-Z]+$/i.test(value);
}, "Field must contain only letters");
});
//The function in question
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
//Function to switch between the different pages in the menu.
function toggle(id) {
if(id=='LoginPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='RegisterPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='GamePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
}
return false;
}
If you're looking to override the form's natural submit behavior, you can do this:
$(document).ready( function(){
$('#registerForm').submit( function(e){
e.preventDefault(); // suppress natural submit behavior
submitUser(); // your function
});
});
And since you're already using jQuery, you can greatly simplify your toggle code. For each block like this:
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
...you can instead do this:
if( id === 'WelcomePage' ){
$('#'+id).show();
$('#LoginPage, #RegisterPage, #GamePage').hide();
}
Or even more generally, handle all your toggling cases with one line:
function toggle(id){
$('#LoginPage, #RegisterPage, #GamePage, #WelcomePage')
.hide()
.filter('#'+id).show();
}
You can try adding this to your onclick event (on your 'submit' button):
onclick="javascript:return SubmitFunction();"
OR in your form tag (For normal submit button):
onSubmit="javascript:return SubmitFunction();"
Make sure you are returning true or false in your function. if false is returned page won't reset/refresh.
When the page refreshes or changes, the JavaScript variables are reset... Thats the unfortunate truth. Make sure the function that the form is on returns false to stop it from changing the page - so SubmitUser() should look like:
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
return false;
}
Now, to change pages look at using jQuery.html (Link) to load content in without actually changing the page (or jQuery.load (Link) to load an actual file, like games.html):

Categories

Resources