MrSun's Website

A Site to Record and Share

CSS configuration via javascript 1

This time I try to change the padding and background color of a picture with javascript coding, like this below. The final result is when I drag the spacing button, the picture padding is changing as well, and if I change the base color, the picture background color is changed as well.

The main two knowledge points I am going to practise are Dataset JavaScript and addEventListener.

The dataset JavaScript, per the definition, is a document-oriented module (DOM) property to access the data attribute and set it on the JavaScript element. It’s a DOM interface to set data elements to the application using JavaScript language. I have seen the usage of dataset quite a lot in online tutorials and others’ projects but haven’t dug deeper on how it works and how it can be used to archive what I want.

AddEventListener is another one that is used quite frequently in JavaScript, but what I have practised much is click event or some keyboard events. In this practice, I am using change event to get the result I want after the action is completed, and also mousemove event to make the change happening while I am dragging the button.

Here are the two components that can be changed:

<input type="range" min="10" max="200" value="10" name="padding" data-sizing="px">

<input type="color" name="background" value="#FFFF00">

and here is what I am using dataset and addEventListener to get what I want:

const suffix = obj.dataset.sizing || '';

document.querySelector(".img").style.setProperty(obj.name, obj.value +`${suffix}`);

It’s a very simple task but without the knowledge of these two points, it might be very hard. I have put the code into my Github (again I am new to Github as well and I am thinking it might be worth spending some time and effort on that as well as there are so many resources for developers and is quite a good place to store codes) as a reference to compare between when I am learning these new concepts freshly and when I get quite familiar with these common concepts with JavaScript coding.