I have a button and I want to be able to change the background of my html file via the button click, and then again change back to original URL when clicked again.
So I created a map with key/values. First key will be original background, and it's value will be the new background. And opposite with the second key/value pair.
Below is my code
const nextBackgroundImageUrl = {
"url('../images/pexels_bg.jpeg')" : url('/images/bbyshrk.jpg'),
"url('../images/bbyshrk.jpg')" : url('/images/pexels_bg.jpeg')
}
function changeImg() {
const currentBackgroundUrl = elem.style['background-url'];
elem.style['background-url'] = nextBackgroundImageUrl[currentBackgroundUrl];
}
It seems this should work? Except, I am getting an error in the console:
index.html:197 Uncaught ReferenceError: url is not defined
in reference to the VALUE of the second key/value pair, url('/images/pexels_bg.jpeg')
This file definitely exists.
Is it that URL cannot be used as a value to a key? Or am I missing something else.
Any advice helps, thanks.
Here the url in value is getting considered as a variable. Change it to a string
const nextBackgroundImageUrl = {
"url('../images/pexels_bg.jpeg')": "url('/images/bbyshrk.jpg')",
"url('../images/bbyshrk.jpg')": "url('/images/pexels_bg.jpeg')"
}
Related
I am making a script that changes settings on twitch.tv
When I need to check if a toggle button is checked, this is simple enough. But the method name to catch the true, false value on the .checked, changes every time I load the page.
var latencyButton = document.getElementsByClassName("tw-toggle__input")[0];
if(latencyButton.__reactEventHandlers$kupq2smnamk.checked)
latencyButton.click();
console.log("Latency Changed");
}
It's the __reactEventHandlers$(This part) that changes so I have something to start off on.
Edit: added the HTML that surrounds the toggle button
<div data-test-selector="low-latency-toggle" class="tw-align-items-center tw-flex"><label class="tw-drop-down-menu-input-item__label tw-flex-grow-1 tw-mg-r-2" for="f8960cb3c79352dd6dd718358e42a812">Low Latency</label><div class="tw-toggle" data-test-selector="low-latency-toggle"><input type="checkbox" class="tw-toggle__input" id="f8960cb3c79352dd6dd718358e42a812" data-a-target="tw-toggle"><label for="f8960cb3c79352dd6dd718358e42a812" class="tw-toggle__button"><p class="tw-hide-accessible">Low Latency</p></label></div></div>
Is there a way to get the checked value without the name of the method? or like a way to get the method name to use in a variable?
Thanks for you time
-Crysal
You could maybe try using filter and indexOf to find the function name. Something like:
let el = document.querySelector(".tw-toggle__input");
let reactHandlerName = Object.keys(el).filter((item) => item.indexOf('__reactEventHandlers')>=0);
let reactHandler = el[reactHandlerName[0]]; // this should be the function name
I'm creating a discord.js bot that needs to read some json
but I've stumbled upon a little problem. In my code I have a function that gets the champion name, then it applies it to the link ex. if user types !champion Yasuo it will search Yasuo.json. But when I'm requesting the JSON and reading it, I want to get a certain key, the lore of the champion. But the path looks like this ex. data.Yasuo.lore; Because in my code I have a variable that gets the champion name i want to apply it to the key path as well, but when I execute it it gives an error that the path couldn't be found because the path is res.data.championName.lore; such key doesn't exist.
What can I do with it? How can I apply a variable to the key path?
Code:
function getChampion(championName){
var url = `http://ddragon.leagueoflegends.com/cdn/10.14.1/data/en_US/champion/${championName}.json`
request(url, (error, head, body)=>{
var res = JSON.parse(body);
var championDesc = res.data.championName.lore; //I want this to be for ex. res.data.Yasuo.lore; I want it as a variable.
console.log(championDesc);
})
}
You'll want to put the variable inside of brackets ([]) to correctly access the value within the JSON object. Here is an example of how that would work with the code you provided:
function getChampion(championName){
var url = `http://ddragon.leagueoflegends.com/cdn/10.14.1/data/en_US/champion/${championName}.json`
request(url, (error, head, body)=>{
var res = JSON.parse(body);
var championDesc = res.data[championName].lore; //I want this to be for ex. res.data.Yasuo.lore; I want it as a variable.
console.log(championDesc);
})
}
I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);
I have an HTML table with the id "roster1" that allows users to add table rows with a button click, and I am attempting to save the table state via a "Save" button that runs the following piece of code:
function saveRoster () {
localStorage.setItem('rosterPd1','');
var roster = document.getElementById ('roster1');
localStorage.setItem('rosterPd1', roster);
}
If I input some static value into 'rosterPd1', then I can use the information written to localStorage with no problem. However, when I attempt to save the table by using the above code, I get [object HTMLTableElement] returned... which is CORRECT, but not particularly useful!
Can someone point me in the right direction on what I would have to do to get localStorage to save the contents of the table itself?
You can only save Strings to Storage, but it seems for what you're trying to do, innerHTML will suffice;
function saveRoster() {
var roster = document.getElementById('roster1');
if (!roster) return; // not found
localStorage.setItem('rosterPd1', roster.innerHTML); // store innerHTML
}
function loadRoster() {
var roster = document.getElementById('roster1');
if (!roster) return; // not found
roster.innerHTML = localStorage.getItem('rosterPd1'); // get+apply innerHTML
}
As for why you're getting [object HTMLTableElement], this is what happens when you call toString on a JavaScript reference to a <table>.
document.createElement('table').toString() // "[object HTMLTableElement]"
I'm designing a web app for Document Managers, and there is a 'settings' page, where the user sees a pair of checkboxes formatted to look like the iphone toggle buttons. they work and all, but whenever the user leaves the website or refreshes the page the state of those buttons is reset back to the default. is there a way to save the state of them using localStorage or do i need to use cookies? EDIT in the JavaScript file (code shown below) there are two functions, one called saveSettings and the other loadSettings, but if i have to do it all in one function then please tell me. END OF EDIT any help at all would be greatly appreciates. so far i have;
localStorage.CheckboxName = $('#CheckboxName').val();
to save the checkbox to localStorage and;
$('#CheckboxName').val(localStorage.CheckboxName);
but it won't save. Am i doing something wrong?
EDIT
here's the HTML code of the two checkboxes;
<li style = 'color: #FFFFFF;'>Notifications<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'notifications' id = 'notifications' /></span></li>
<li style = 'color: #FFFFFF;'>Preview<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'preview' id = 'preview' checked = "true" /></span></li>
END OF EDIT
Any help would be amazing, thanks in advance x
I'm not sure, but I've always believed that it was like this :
window.localStorage.setItem('CheckboxName', $('#CheckboxName').val());
$('#CheckboxName').val(window.localStorage.getItem('CheckboxName'));
You could try the following
$("#CheckboxName").is(':checked')?'checked':'not' and save the output, seems to be what is suggested here:
How to use local storage to retain checkbox states for filtering items
To store an Item just remember that the store only holds strings.
Eg.
var val = $('#CheckboxName').val();
window.localStorage.setItem(key, JSON.stringify(val));
So when you read the value back you need to deserialize the string.
var str = window.localStorage.getItem(key);
var obj = $.parseJSON(str);
Or you could just do string comparison whatever suites your needs better in your case what I would do is store an object of id value pairs in one storage key and deserialize them all to work with proper object
Eg.
var val = {
CheckboxName1: true,
CheckboxName2: false,
CheckboxName3: false, // ect....
};
window.localStorage.setItem(key, JSON.stringify(val));