15/40 - AJAX to update CSS Dynamically
- christophernmiller
- Feb 19
- 1 min read
Exploring AJAX functions on my hosting environment, I enjoyed this styling effect to dynamically update a fixed background image when the user hovers over it.
AJAX and CSS background-image manipulation
Almost like a slider or carousel but because we aren't reloading the entire page you can dynamically update its background content based on user interactions.
carCard.addEventListener("mouseover", function() {
const bgImage = this.getAttribute('data-bg-image');
document.body.style.setProperty('background-image',
`url(${bgImage})`, 'important');
dimOtherCards(this);
});
The code below resets the background image to the default I chose. The important piece is the 'important' attribute, which overrides hard-coded CSS.
carCard.addEventListener("mouseout", function() {
document.body.style.setProperty('background-image',
`url(${initialBgImage})`, 'important');
resetCardDim();
});
Comentários