How to get method that changes name in javascript - javascript

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

Related

Jquery <<S.fn.init [selector]>> in Java Script Vanilla

For this project, I want to change the logic written in jquery with that in js vanilla.
My code looks like this
Based on the information from the input using the event keydown,
I call a function through which I do a search in api.
var selectedUsers = [] //empty array
$('#userSearchTextbox').keydown((event)=>{
var textBox = $(event.target);
var value = textBox.val();
//Function which search in api
searchUsers(value);
});
//Search in array function
function searchUsers(searchTerm){
$.get("/api/users",{search:searchTerm},results =>{
outputSelectableUsers(results,$('.resultsContainer'));
});
}
After I call another function outputSelectableUsers
which will call 2 functions one that displays the data in HTML and one that creates an array of values.
function outputSelectableUsers(results,container){
results.forEach(results => {
//Call function which will render the html
var html =createUserHtml(results,false);
/*
Here is the problem, as seen using jquery element variable selects html variable which render function
*/
var element = $(html);
/*
with jquery, I managed to select the variable and assign it a click event that when I click it calls the function that adapts the array with data
from each API call
*/
element.click(()=>userSelected(results))
//append content to the html selector
container.append(element);
});
}
//Function which will update the array
function userSelected(user){
selectedUsers.push(user);
}
This is what the visible result looks like
And when I click on one of the cards, the area adapts to the user's values.
values ​​that I take from the array and enter them in the database.
I managed to convert everything to js using fetch instead of ajax jquery and changed the selectors and events with vanilla js code.
But the problem is I couldn't find a way to change this piece of code.
var html =createUserHtml(results,false);
var element = $(html);
console.log(element)
element.click(()=>userSelected(results))
container.append(element);
at consol.log (element) I observed asata in the console.
The question is could I choose the element with js vanilla and get the same result as in the jquery version. To use Js Vanilla code instead of
var element = $(html);
element.click(()=>userSelected(results))
let users_id = results._id;
let html = createUserHtml(results,users_id ,false);
container.insertAdjacentHTML('beforeend',html);
//Identify each element by a unique selector
document.querySelector(`[data-selectorTab ="${results._id}"]`).addEventListener('click',()=>{
userSelected(res)
})
I solve this by adding a data attribute to dinamically generated elements,using this data atribute I can make a individual selector for each user.

Creating a const with JS for background url to change background

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')"
}

Unable to retrieve dynamically generated content from localStorage

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]"

How do you save a Checkbox State in localStorage

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));

jQuery.Data set's or get's wrong item

I am using something similair to this:
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", []);
}
And to add data:
var data=inputField.data("FieldLocalizationStrings");
data.push({Language:inputField.attr("language"),Value:inputField.val()});
But when i try to retreive, it seems to ignore on which DOM element it has been saved and just loads it like it was all saved on the same element. Anyone an idea why this would happen? i have used the same technique before and it proved to work, but now i can't figure out why this is hapening.
I confirmed it does not save it to multiple input fields, but when loading it acts like it is.
Update
Added a fiddle here
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", [
{
Language:inputField.attr("language"),
Value:inputField.val()
}
]);
//If later you want to append to the data
inputField.data("FieldLocalizationStrings").push({/* Your data */})
}
http://api.jquery.com/jQuery.each/ - as for documentation you'll get value as second parameter. If you want set data for an element you should use this.

Categories

Resources