How to change a javascript variable with HTML?
I am making a chrome extension which adds icons to certain URLs, so I would like to make a slider to adjust the size of the icon in the popup.html
.
The HTML of the slider looks like this:
<div class="slidecontainer"> <input type="range" min="1" max="3" value="2" class="slider" id="myRange"> </div>
But for the slider to work, it needs some javascript code.
In the javascript file, I made a variable called size
. I need the javascript to change the size
variable according to the position of the slider.
var size = "/images/icon16.png"; var imageURL = "chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + size;
So I am thinking of a script that checks for myRange
, and if it is 1
, 2
, or 3
, it sets size
to corresponding string:
"/images/icon16.png"
"/images/icon48.png"
"/images/icon128.png"
The catch is that I don’t know how to implement this in my code, so any help or explanation would mean the world to me …
You could save your strings in an array:
var myPaths = [ "/images/icon16.png", "/images/icon48.png", "/images/icon128.png" ]
And access your slider input like this:
var slider = document.getElementById("myRange");
so that slider.value
will be the value of the input
.
You could listen out for the change
event on the slider, and then set your size
variable accordingly.
Full code:
var myPaths = [ "/images/icon16.png", "/images/icon48.png", "/images/icon128.png" ]; var size = "/images/icon16.png"; var slider = document.getElementById("myRange"); slider.addEventListener("change", updateSize); function updateSize() { size = myPaths[slider.value - 1]; }
In short: document.getElementById("myRange").value;
.
You can read more about sliders and getting the value of the slider here. If you want to get the value every time the slider is utilised:
document.getElementById("myRange").addEventListener("input", (evt) => { console.log(evt.target.value); })
- Attach an
onchange
event listener to theinput
tag. - Declare
enum
as follows:
let enum = { 1: "/images/icon16.png", 2: "/images/icon48.png", 3: "/images/icon128.png" }
- Write something like this in the callback:
var size, imageURL; let enum = { 1: "/images/icon16.png", 2: "/images/icon48.png", 3: "/images/icon128.png" } let inputrange = document.querySelector('input[type=range]'); inputrange.addEventListner("change", function() { size = enum[inputrange.value]; imageURL = `chrome-extension://${chrome.i18n.getMessage("@@extension_id") + size}` ; }) ;