I know this should be easy.. but im still learning JS :)
this code works fine, but currently I will have to repeat this about 20 times, just changing the L50C object, and the xp_50...
let L50C = document.getElementById('lvl50');
chrome.storage.sync.get('L50color', function(data) {L50C.setAttribute('value', data.L50color);
});
let L60C = document.getElementById('xp_60');
chrome.storage.sync.get('L60color', function(data) {L60C.setAttribute('value', data.L60color);
});
L40C.onchange = function(element) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.insertCSS(
tabs[0].id,
{code: ".xp_40 {border: 1px solid " + element.target.value + " !important;} .xp_40 .icon {color: " + element.target.value + " !important;}"});
});
};
L50C.onchange = function(element) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.insertCSS(
tabs[0].id,
{code: ".xp_50 {border: 1px solid " + element.target.value + " !important;} .xp_50 .icon {color: " + element.target.value + " !important;}"});
});
};
(im using #60 to test) so.. if I change the id="xp_60" like this...
<div class="lvl_inp_cont">Level 60: <input id="xp_60" type="text" class="lvl_input" maxlength="7"></div>
can i call a function to repeat... like this:
L60C.onchange = swap(element);
function swap(element) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.insertCSS(
tabs[0].id,
{code: "." + element.id + " {border: 1px solid " + element.target.value + " !important;} ." + element.id + " .icon {color: " + element.target.value + " !important;}"});
});
};
see so instead of all that code, i can just set it to one re-usable code? I feel like the swap function looks right (if not i can fix it) - its just how do I "call" or set the onchange to that function?
Thanks!!
EDIT: am i close?
const obj = {L40C, L50C, L60C, L70C};
for(let num = 40; num < 150; num+=10) {
let obj['L' + num + 'C'] = document.getElementById('xp_' + num);
}
L60C.onchange = swap(element);is calling the method right away as you may have seen. When you set an event handler the first argument for the handler (which you have aselementin both examples is actually theevent.event.targethas the reference to the element that triggered the event. So settingL60C.onchange = swap;is closer to what you want, but you'll still have to make some changes.L50Crefers to#lvl50andL60Crefers to#xp_60, and not, for example, to#lvl60? That'll make DRY code harder.xp_40refers to a class name ofxp_40(in the upper code), but in the bottom you're concatenating with"." + element.id, which is anid, not aclassName? (alsoelementin your lower code actually refers to the event, not the element, see answer)