How to get my button to work using javascript? - javascript

I am creating an Google chrome extension and I am trying to get my stop/stop logging button to work within my function named Logger. When the button is pressed it doesn't react to the function I wrote, Currently it is displaying the stop-button but I want it to display the start-button when clicked. I hope I explained that to some understanding but do anyone possibly know why my function is not working?
Below is my current javascript function and html :
popup.js
//attempt to get start/stop logging buttons to work
function Logger(isLogging, notLogging) {
if (isLogging = true, notLogging = false) {
addRow();
document.getElementById("click-start").style.display = "block";
document.getElementById("click-stop").style.display = "none";
}
if (isLogging = false, notLogging = true) {
document.getElementById("click-start").style.display= "none";
document.getElementById("click-stop").style.display= "block";
}
}
//button to start logging
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-start").addEventListener("click", Logger(true, false));
});
//button to stop logging
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-stop").addEventListener("click", Logger(false, true));
});
popup.html
<!--Start button of logging-->
<button class="button button1" id="click-start" >
<u> Start Logging </u>
</button>
<!--Stop button of logging-->
<button class="button button2" id="click-stop" >
<u> Stop Logging </u>
</button>
Image of current output--button currently doesnt react

This may help to get the core functionality working, this implementation can be much improved
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//attempt to get start/stop logging buttons to work
function Logger(isLogging) {
console.log(isLogging)
if (isLogging) {
btnStart.style.display = "block";
btnStop.style.display = "none";
}else{
btnStart.style.display = "none";
btnStop.style.display = "block";
}
}
//button to start logging
document.addEventListener("DOMContentLoaded", function () {
btnStart.addEventListener("click", function() {Logger(false)});
btnStop.addEventListener("click", function() {Logger(true)});
});
You have to try to keep the queries to the DOM to a minimum.
Have a look at the toggle method it will help to make your code a bit leaner and easier to maintain

I'm not sure if the Logger function gets executed if you use it like this in the addEventListener.
Maybe you can give it a try like this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-start").addEventListener("click", function () {
Logger(true, false))
};
});

Related

Decided to work smart by creating a JS to link to multiple HTML pages but on doing so a button doesn't seem to work. can't seem to understand why

HTML CODE (index.html)
<html>
<div id="mode"></div>
<script src="/js/install.js"></script>
<script src="/js/create.js"></script>
</html>
create.js function to create an Install button
<html>
<div id="mode"></div>
<script src="/js/install.js"></script>
<script src="/js/create.js"></script>
</html>
This specific line doesn't seem to trigger after the button is clicked but it would when simply written manually.
(create.js)
window.addEventListener("DOMContentLoaded", (e) => {
var f = document.createElement("A");
f.id = "m6";
f.className =
"add-button waves-effect red waves-light btn white-text right install";
f.textContent = "INSTALL APP";
document.getElementById("m4").appendChild(f);
});
This File doesn't seem to trigger when using create.js to create the code but if done manually functions as should.
(install.js)
let deferredPrompt;
const addBtn = document.querySelector(".add-button");
addBtn.style.display = "none";
const addTxt = document.querySelector(".add-text");
addTxt.style.display = "none";
window.addEventListener("beforeinstallprompt", (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
addBtn.style.display = "block";
addTxt.style.display = "block";
addBtn.addEventListener("click", (e) => {
// hide our user interface that shows our A2HS button
addBtn.style.display = "none";
addTxt.style.display = "none";
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === "accepted") {
console.log("User accepted the A2HS prompt");
} else {
console.log("User dismissed the A2HS prompt");
}
deferredPrompt = null;
});
});
});
Would deeply be grateful to anyone that can help with this.

Chrome Extension Popup Resets On Closing

I'm trying to figure out how to make a play/pause functionality for my chrome extension. I've figured it out and it works however, for usability I now am trying to get the popup window to:
Keep the checkbox checked if it was before closing the popup.
Keep the content that popup.js wrote into a span tag before closing the popup.
My popup.html is:
<script src="popup.js"></script>
<div class="container">
<div class="checkbox">
<p>Check the box to pause the extension</p>
<input type="checkbox" id="switcher" name="switcher">
<p><span id="extensionStatus"></span></p>
</div>
<a id="submit" href="#">Save</a>
</div>
And my popup.js is:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
if(switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
chrome.storage.sync.set({'status': status});
chrome.storage.sync.get('status', function (result) {
status = result.status;
updateStatus.innerHTML = "Current Status: " + status;
if(status == "paused") {
switcher.checked = true;
}
});
});
});
I set have to set the value in storage as I also use the value to do other code on content-script file.
Basically where the line that writes the innerHTML and then the line that sets the checkbox to checked run fine when the popup is open and then as soon as you close the popup and reopen obviously the session resets.
I know it needs something like this in the popup.js instead but I am not quite sure what to put in the function in the background.js as I can't/don't know how to access the popup DOM from background.js:
var backgroundPage = chrome.runtime.getBackgroundPage();
backgroundPage.savePopup();
I don't know how extension storage works but here's a demo which works with local storage. Maybe it can help you with the extension.
Demo
document.addEventListener('DOMContentLoaded', function() {
if (localStorage.getItem('status') == 'paused') {
switcher.checked = true;
}
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
console.log('staus:', localStorage.getItem('status'));
if (switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
localStorage.setItem('status', status);
});
});

Event Listener not working in cookie modal

first time caller here, please be gentle..
I am in the process of my JavaScript reflection and having a problem with the cookie modal. You need to be able to have the cookie pop up upon entering the site, the user needs to click ok, it is stored locally, and doesn't pop up if the user refreshes the browser.
I have created a basic modal and written the JavaScript, which partly works, but the eventHandler isn't working.
The cookie value is false, which you can see in the console, but when you click the button, it doesn't turn to true.
I have put the code below and if anyone could help I'd really appreciate it.
<div id ="overlay">
<div class="modal">
<p>
</p>
</div>
<button class="settings_button">CHANGE SETTINGS</button>
<button class="modal_accept_button">ACCEPT COOKIES</button>
<button class="modal_accept_button">Accept</button>
</div>
let modalObject = document.querySelector(".modal");
let modalSettings = document.querySelector('.settings_button');
let modalAccept = document.querySelector('.modal_accept_button');
let modalOverlay = document.querySelector("#overlay");
function showModal() {
modalObject.classList.remove('deactive');
modalOverlay.classList.remove('deactive');
}
function disableModal() {
modalObject.classList.add('deactive');
modalOverlay.classList.add('deactive');
}
localStorage.setItem('cookie', 'false');
window.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('cookie') == 'true') {
console.log("Cookie is already in place.");
} else if (localStorage.getItem('cookie') === null ||
localStorage.getItem("Cookie accepted") == 'false') {
console.log("Cookie has been not yet been accepted.");
showModal();
modalAccept.addEventListener('click', () => {
localStorage.setItem('cookie','true');
disableModal() ;
});
}
});
You have localStorage.setItem('cookie', 'false'); in your code and this changes your ls to false every time that your codes run, just remove it and I think it's better if you save your local storage in a variable then use that variable in your if statement:
const modal = document.querySelector('.modal');
const acceptBtn = document.querySelector('#acceptCookies');
(() => {
const isCookieAccepted = JSON.parse(window.localStorage.getItem('cookie'));
if (isCookieAccepted) {
alert(`Cookie status: ${isCookieAccepted}`)
} else {
modal.classList.add('show')
}
})();
acceptBtn.addEventListener('click', () => {
window.localStorage.setItem('cookie', true);
modal.classList.remove('show')
})
In your code, you have a line that sets it to false:
localStorage.setItem('cookie', 'false');
This will always set it to false every time you go to that page. So even if you set it to true, when you refresh it will be back to false again.
Removing that line should work, as you dont need to set it to false

Showing warning with timeout when opening external links

I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}

Toggling on the first click

I've tried two different methods of toggling the play/pause button on my player, neither of which work on the first click, for some reason.
This one, supposedly checks the status of the audio to see if it's paused or ended:
function togglePlayPause() {
var audioPlayer = document.getElementsByTagName('audio')[0];
var playpause = document.getElementById("playpause");
if (audioPlayer.paused || audioPlayer.ended) {
playpause.title = "pause";
playpause.innerHTML = "pause";
}
else {
playpause.title = "play";
playpause.innerHTML = "play";
}
}
Or I've tried this one, which just toggles via the onClick toggle(this):
function toggle(obj) {
if (obj.className== 'playButton') {
obj.className = 'pauseButton';
obj.title = "PAUSE";
obj.innerHTML = "PAUSE";
} else {
obj.className = 'playButton';
obj.title = "PLAY";
obj.innerHTML = "PLAY";
}
}
Neither toggle the first time the button is clicked, although the first method does change from the default inner "PLAY" to "play", so I guess that's something:
<div title="play" class="playButton" id="playpause">PLAY</div>
In both methods, subsequent clicks work fine. Any idea why this is happening? Could it have something to do with the way the audioPlayer variable is called? The array starts from 0. (I'm clutching at straws.)
Many thanks as usual!
I would go without creating functions, I would check if the link is clicked then proceed to the events that would be fired.
so something like $("#start").click(function(){}); in can be tried.
First, have the jQuery library included in your HTML header.
Then create a new javascript file, included it as well (usually this is put after the jQuery included)
In your new javascript file write the following
$(document).ready(function() {
$("#start, #stop, #play, #pause").click(function() { //you can have more or less selectors (selectors are the ones with #)
//Your code goes here
});
});
Here is a fiddle for that solution. http://jsfiddle.net/JRRm2/1/ (tidier text: http://jsfiddle.net/JRRm2/2/)

Categories

Resources