Categories
JavaScript Answers

How to Set a CSS Property of an HTML Element with JavaScript?

Sometimes, we want to set a CSS property of an HTML element with JavaScript.

In this article, we’ll look at how to set a CSS property of an HTML element with JavaScript.

Set a CSS Property of an HTML Element with JavaScript by Setting the style Property

We can set a CSS property of an HTML element with JavaScript by setting a property of the style property.

For instance, we can write:

const element = document.createElement('div');  
element.textContent = 'hello world'  
element.style.backgroundColor = "lightgreen";  
document.body.append(element)

We call document.createElement with 'div' to create a div element.

Then we set the textContent to a string to add some text into the div.

Next, we set the style.backgroundColor property to set its background color.

Any CSS properties with multiple words are in camel case instead of kebab case in CSS.

Then finally, we call document.body.append to append the div into the body element.

Set a CSS Property of an HTML Element with JavaScript by Setting the cssText Property

Another way to set the style of an HTML element with JavaScript is to set the style.cssText property to a string with some CSS styles in it.

For instance, we can write:

const element = document.createElement('div');  
element.textContent = 'hello world'  
element.style.cssText = 'background-color: lightgreen';  
document.body.append(element)

We set element.style.cssText to a string with some CSS styles.

The string just has regular CSS code to set the styles.

Therefore, we get the same result as we had in the previous example.

Conclusion

We can set the CSS styles of an HTML element by setting the style properties within the style property or the style.cssText property to set the CSS text.

Categories
JavaScript Answers

How to Get the First and Last Day of the Current Month with Moment.js?

Sometimes, we want to get the first and last day of the current month within our JavaScript app.

We can do this easily with moment.js.

In this article, we’ll look at how to get the first and last day of the current month with Moment.js.

Use the Moment.js startOf and endOf Methods

We can use the startOf method to get the first day of the current month.

And we can use the endOf method to get the last day of the current month.

For instance, we can write:

const startOfMonth = moment().clone().startOf('month').format('YYYY-MM-DD hh:mm');  
const endOfMonth = moment().clone().endOf('month').format('YYYY-MM-DD hh:mm');  
console.log(startOfMonth)  
console.log(endOfMonth)

We call moment to create a Moment object with the current date and time.

Then we call clone to clone that object.

Then we call startOf with 'month' to return the first day of the current month.

And then we call format to format the date into the human-readable YYYY-MM-DD format.

Likewise, we do the same with the endOf method to get the last day of the current month.

If the current month is April, 2021, then we should get:

'2021-04-01 12:00'

for startOfMonth .

And endOfMonth should be:

'2021-04-30 11:59'

startOf and endOf also accepts 'year' , 'week' , and 'day' as arguments to get the first and last year, week, or day of the given date and time.

Conclusion

We can get the first and last day of the current month easily with the Moment.js’s startOf and endOf methods respectively.

Categories
JavaScript Answers

How to Remove the First and the Last Character of a JavaScript String?

Sometimes, we want to remove the first and last characters of a JavaScript string.

In this article, we’ll look at how to remove the first and last characters of a JavaScript string.

Use the String.prototype.substring Method

We can use the JavaScript string’s substring method to return a string that’s between the start and end indexes.

The start index is included but the end index isn’t.

To use it, we write:

const str = "/installers/";  
const result = str.substring(1, str.length - 1);  
console.log(result);

to call substring with the start and end index respectively.

str.length — 1 is the end index because we only want to return the string up to the 2nd last character.

Therefore result is 'installers' .

Use the String.prototype.slice Method

We can also use the JavaScript string’s slice method to return a string between the start and end indexes.

For instance, we can write:

const str = "/installers/";  
const result = str.slice(1, -1);  
console.log(result);

to call slice with the start and end index of the str we want to include in result .

Index -1 is the last index of the string, and it’s not included in the returned string like substring .

Therefore, result is the same as the last example.

Conclusion

We can use the JavaScript string slice or substring method to extract a string within the given start and end indexes.

The character at the end index isn’t included in the returned string with either method.

Categories
JavaScript Answers

How to Track the User’s Mouse’s Position with JavaScript?

Sometimes, we want to track the user’s mouse’s position with JavaScript.

In this article, we’ll look at how to track the user’s mouse’s position with JavaScript.

Get the Mouse’s Position with the clientX and clientY Properties

We can listen to the mousemove event which is triggered whenever we move the mouse.

Then from the mousemove event object, we can use the clientX and clientY properties to get the x and y coordinate of the mouse cursor on the page.

For instance, we can write:

document.onmousemove = (event) => {  
  const {  
    clientX,  
    clientY  
  } = event  
  console.log(clientX, clientY)  
}

to log the x and y coordinates of the mouse in pixels.

We set an event handler function as the value of the document.onmousemove property.

We attach the event listener to document because we want to listen to the mouse movement on the page.

The method takes the event parameter, which is the mousemove event object.

In the event handler function, we get the clientX and clientY properties to get the x and y coordinates of the mouse cursor’s location on the page.

We can also attach the event listener with the addEventListener method.

For instance, we can write:

document.addEventListener('mousemove', (event) => {  
  const {  
    clientX,  
    clientY  
  } = event  
  console.log(clientX, clientY)  
})

We call addEventListener with 'mousemove’ to listen to the mousemove event.

And then we get the x and y coordinates of the mouse cursor the same way.

Now we should see the x and y coordinates of the mouse cursor logged.

Conclusion

We can use the mousemove event object’s clientX and clientY properties to get the x and y coordinates of the mouse cursor on the page in pixels.

Categories
JavaScript Answers

How to Match an Exact String with JavaScript?

Sometimes, we want to find an exact string within our JavaScript code.

In this article, we’ll look at how to find an exact string with JavaScript.

Using the String.prototype.match Method

We can use the JavaScript string instance’s match method to search for a string that matches the given pattern.

For instance, we can write:

const str1 = 'abc'
const str2 = 'abcd'
console.log(str1.match(/^abc$/))
console.log(str2.match(/^abc$/))

to call match with a regex that matches the exact word.

^ is the delimiter for the start of the word.

And $ is the delimiter for the end of the word.

Therefore, the regex matches the exact word in between the delimiters.

The first console log should log 'abc' as a match.

And the 2nd console log should log null .

We can convert the matched strings to an array.

For instance, we can write:

const str1 = 'abc'
console.log([...str1.match(/^abc$/)])

We use the spread operator to convert the match object to an array since the match object is an iterable object.

Conclusion

We can match an exact string with JavaScript by using the JavaScript string’s match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.