Javascript: reload default after userscript - javascript

I have a user script that does some stuff after clicking a button. By clicking the same button again (like a toggle button), I want it to 'revert' back to default. By default I mean the on page load content. Check my code:
var myTbl = document.getElementsByClassName("myTable")[0];
var myCells = myTbl.getElementsByTagName("td");
myCells[2].innerHTML = "<span id='myButton' class='button'>Do something / Revert</span>";
document.getElementById("myButton").addEventListener("click", doSomething, false);
function doSomething() {
// do some stuff with myTbl
document.getElementById("myButton").removeEventListener("click", doSomething, false);
document.getElementById("myButton").addEventListener("click", revertToDefault, false);
}
function revertToDefault() {
// location.reaload();
}
I could do it with location.reaload();, but that's not what I want. I would prefer to save the default on load content in a variable like I did with the variable myTbl var myTbl = document.getElementsByClassName("myTable")[0]; and preserve that default content and then simply save that default content in the variable myTbl myTbl = defaultTbl; when executing the revertToDefault() function. What's the correct code to do that? Is there a better way of doing that, perhaps without the need of saving everything in a variable?

A possible working solution:
var myTbl = document.getElementsByClassName("myTable")[0];
var defaultTbl = myTbl.innerHTML; // this way defaultTbl remains intact while manipulating myTbl object
function revertToDefault() {
myTbl.innerHTML = defaultTbl;
}

Related

window. onload=function() just works without cached DOM

The product image is displayed as inline SVG and receives a new color for specific paths, depending on the dropdown selection.
"use strict";
window.onload=function(){
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
}
But this Javascript code works only, if the page was read in the DOM for the first time. If you reload this page with F5, this will not lead to any errors in the console, but not to the desired result.
EDIT: Nothing here worked for me. But I noticed that if I delete the `woocommerce_recently_viewed``cookie, that the systems works fine. But how to fix such a thing?
It's generally bad practice to use onload = ... You should instead try using addEventListner("load", ...)
The reason your script does not run, is because it gets compiled after the page has been fully loaded, so you should also check if the load event has already been fired.
"use strict";
if(document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);
function onLoad(){
console.log("Doing on load stuff here...");
}
Try this instead and see if it works:
window.addEventListener('DOMContentLoaded', (event) => {
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
});

how to open link in external window with click on anchor tag with javascript?

This is probably such a noob question, but I can't get it to work.
I want to open external window link by clicking on anchor tag, but I keep getting error that myFunction() is not defined.
Open link
js
$(document).ready(function() {
$('#searchEng').click(function() {
const engine = document.getElementById('engine');
var en_ = engine.val();
if (en_ == "firefox")
{
function myFunction() {
var url = "https://www.mozilla.org/en-US/firefox/new/";
window.open(url,'_blank');
};
}
});
));
Why is it undefined?
I have .js included because other stuff works.
you can remove function inside click function
$(document).ready(function(){
$('#searchEng').click(function() {
const engine = document.getElementById('engine');
var en_ = engine.val();
if (en_ == "firefox")
{
var url = "https://www.mozilla.org/en-US/firefox/new/";
window.open(url,'_blank');
}
});
Open link
You declared myFunction inside another function, which makes it a local variable of that function. Local variables aren't available outside the function where they were defined.

Call a javascript function throught URL

I have a website with tabs, where each tab is in fact in the same table with an atribute that show it or not. Then a javascript function would change the attribute when you press on the tab.
The function is something like this:
function showHide(ID) {
switch (ID) {
case 'main':
document.getElementById('main').style.display = 'block';
document.getElementById('abstracts').style.display = 'none';
break;
case 'abstracts':
document.getElementById('main').style.display = 'none';
document.getElementById('abstracts').style.display = 'block';
break;
}
return true;
}
Then, the title of the tab is something like
Main
and the tab is
<tr id="main"> ... </tr>
The thing is that I would like to be able to have a URL for a tab, for example http://mypage.com#main or something like that, so when I enter to that URL, the tab main is focussed.
Is that possible?
At the bottom of your page or window.onload, read the hash and call your method.
(function(){
var hash = window.location.hash.substr(1);
showHide(hash);
}());
and if you want the url to change, you probably want to remove the return false.
You can use hashchange event listener here.
eg :window.addEventListener("hashchange", doThisWhenTheHashChanges, false);

open window and run function on that window

I'd like to open a new window, this window has a list of objects, and these objects should be filtered based on a selection from the previous window. I figured I can filter the list through a function, but how do I run said function?
This is what I am able to do:
var popup = window.open('pageURL');
$(popup.document).ready(function() {
// this is where function should be
popup.alert('HelloWorld');
});
But how do I change the alert to a function?
If I have a function on my other app , function test() { alert('HelloWorld'};
How do I run this function from my first app?
Swapping popup.alert('HelloWorld'); with popup.test(); did not work.
You need the reference to the window opened to call functions in the new window, like:
var oNewWindow = window.open("new.window.url", "mywindow");
oNewWindow.onload = function(){oNewWindow.window.newWindowFunction();};
I ended up with this solution
var popup = window.open('http://s234-0057/actiontracker/SiteAssets/Avvik/html/app.aspx');
var readyStateCheckInterval = setInterval(function() {
if (popup.document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
popup.test();
}
}, 50);
Where I check if the popup window is ready, and when it is, cancel check and run function. Solution is from top answer on this question, by #this.lau_
You can write it like this:
function myFunction(){
alert('HelloWorld');
}
var popup = window.open('pageURL');
$(popup.document).ready(function() {
popup.eval(myFunction + "");
popup.myFunction();
});
myFunction in file that contains this code will run in page with pageURL address.

Make an onclick event react different when click second time

I have a button on my website, which plays the music when you click on it and in the same time it changes the text inside of the button (to "Go to SoundCloud".)
I want that button (with the new text on it) to redirect to SoundCloud when I click on it.
Now I got both when click first time, which is redirect to SoundCloud and play the track. (plus it changes the text)
Any ideas, how to solve this problem? Thx!
var links = document.getElementById("playButton");
links.onclick = function() {
var html='<iframe width="100%" height="450" src="sourceOfMyMusic"></iframe>';
document.getElementById("soundCloud").innerHTML = html;
var newTexts = ["Go to SoundCloud"];
document.getElementById("playButton").innerHTML = newTexts;
newTexts.onclick = window.open('http://soundcloud.com/example');
};
Use a variable that indicates whether it's the first or second click.
var first_click = true;
links.onclick = function() {
if (first_click) {
// do stuff for first click
first_click = false;
} else {
// do stuff for second click
}
}
Just redefine the onclick after the first function call.
Put the onclick on the button instead of the html.
document.getElementById("playButton").onclick=window.open('http://soundcloud.com/example');
Another option in some cases is to use a ternary operator and a boolean toggle expression:
let btn = document.querySelector('.button');
let isToggledOn = false;
btn.addEventListener ('click', function(e) {
e.target.textContent = !isToggledOn ? 'Is ON' : 'Is OFF';
isToggledOn = !isToggledOn;
});
newTexts.onclick is not creating a function to open a window, it is simply taking the return value of window.open which is being executed right away.
It should look like:
newTexts.onclick = () => window.open('http://soundcloud.com/example');
Also this will not work as intended because newTexts is not the actual DOM element, you need to attach the new onclick on the element and not the array...
But to other answers in this page, the logic is hard to read, so I'd advise to refactor the logic to be more readable.

Categories

Resources