Sliding through various background options

How can I change backgrounds on a slider without using .style.backgroundImage? Is there a way to do it by adding a class to the slider or some other method?

'use strict'

let backgroundSlides = ['url(\'/images/slider/burger-background.jpg\')',
  'url(\'/images/slider/pizza-background.jpg\')',
  'url(\'/images/slider/soup-background.jpg\')',
  'url(\'/images/slider/sushi-background.jpg\')'
];

let sliderElement = document.querySelector('.slider');
let sliderBtn = document.querySelectorAll('.slider-button');

for (let i = 0; i < sliderBtn.length; i++) {
  sliderBtn[i].addEventListener('click', function() {
    sliderElement.style.backgroundImage = backgroundSlides[i];
  });
}
<div class="slider">
    <div class="slider-btns">
        <input type="radio" name="slider button" id="slider-btn-1">
        <label class="slider-button" for="slider-btn-1"></label>
        <input type="radio" name="slider button" id="slider-btn-2">
        <label class="slider-button" for="slider-btn-2"></label>
        <input type="radio" name="slider button" id="slider-btn-3">
        <label class="slider-button" for="slider-btn-3"></label>
        <input type="radio" name="slider button" id="slider-btn-4">
        <label class="slider-button" for="slider-btn-4"></label>
    </div>
</div>

Answer №1

Utilizing Custom Classes: Assign a unique class to each input and incorporate background images into them.

<style>
  .slider-btn-1 {background-image: url('/images/slider/burger-background.jpg');}
  .slider-btn-2 {background-image: url('/images/slider/pizza-background.jpg');}
  .slider-btn-3 {background-image: url('/images/slider/soup-background.jpg');}
  .slider-btn-4 {background-image: url('/images/slider/sushi-background.jpg');}
</style>

Simply modify the class attribute moving forward.

<script>
let sliderElement = document.querySelector('.slider');
let sliderBtn = document.querySelectorAll('.slider-button');

for(let i = 0; i < sliderBtn.length; i++){
    sliderBtn[i].addEventListener('click', function(){
        sliderElement.className = 'slider ' + sliderBtn[i].htmlFor;//Or another attribute where the className is in
    });
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

What is the easiest way to update the border color of a radio button in Material-UI?

I am looking to customize the appearance of the outer ring on Material UI radio buttons. https://material-ui.com/components/radio-buttons/ Currently, my radio button looks like this: https://i.stack.imgur.com/o67mN.jpg However, I would like it to look ...

How can I connect a click event on one div to trigger another using jquery?

Could someone assist me with the proper terminology? I am interested in clicking one div, which would then automatically trigger the click on another div. For example, if I click on div 1, I want div 2 to be clicked by JavaScript without user interaction ...

I am encountering a 404 error when attempting to make a GET request for a file located in the same directory

Here is the Javascript code that utilizes the get method. The directory contains both files - the HTML file where the JS code resides, and the text file. Below is an image of the console displaying errors. ...

Inconsistency in naming of jQuery CSS properties

Can you explain the reason behind the difference in property names: $(elem).css('padding-top') compared to $(elem).css('marginTop') ? Wouldn't it make more sense if we use: $(elem).css('margin-top') instead? ...

Highcharts facing issues with data rendering

This is the JSON data I have: [ { "project_title":"sdsdsd", "project_ref_id":"112", "amount":"232323.00", "months":"Mar-2015" },{ "project_title":"test project 44", "project_ref_id":"113", "a ...

The issue arises when a variable inside a mat dialog text is not defined properly within an Angular application

I have utilized angular to create a dialog for gathering information and saving it on my back-end. The issue arises when attempting to send the data to the back-end using the post method, as the variable "val" remains undefined. The specific variable in q ...

Is it necessary to re-export a module after modifying an attribute in it in JS/ES6?

From my understanding of the module system, when I use import 'some_module' in a file, I will always receive the same instance of that module and not a new instance each time. However, I am a bit puzzled by a pattern I have observed in certain a ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

Troubles with modifying website background using JavaScript

I'm looking to update my website background using JavaScript, starting with buttons before moving to a drop-down menu. I have the following code that successfully changes the background when the button is clicked: function selectText(test){ var a ...

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

Is there a way to ensure that my mouseenter function does not run when it is currently in the process of running?

Issue at hand: Currently, I am tackling a problem with the mouseenter function $('.filmstrip').bind('mouseenter',function(){ var isRunning = false; var $elem = $(this), width = $elem.width(), ...

"Enhancing user experience with Ajax and seamless page updates

I'm currently in the process of developing a web application that includes a feature to trigger a backend action that may take up to 5 minutes. This backend process will run independently from the web app's front-end and back-end functionalities. ...

How to use jQuery to locate a class within a parent div element

I'm attempting to modify the alt attribute of an image by clicking on it using the add_answer class. Note: The add_answer class is present in multiple div containers. jQuery(function(){ // Add Answer jQuery(".add_answer").click(function(){ ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

Can double curly braces be added within an HTML attribute when using Vue?

Suppose I would like to include <input value='{{default}}'></input> in regular HTML. This will display a textbox with {{default}} as the default input. However, when attempting to achieve the same thing with Vue, it does not work as ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

Tips for adding spaces or tabs in text with HTML/CSS

Here are some options to consider: <pre> ... </pre> or you could also use style="white-space:pre" Are there any other possibilities we should explore? ...

Sharing information linked to dynamically generated HTML elements in MVC5

Currently, I am working on developing an MVC5 application. Within a view, I am dynamically creating HTML elements such as textboxes and dropdown lists using a JSON result returned from the server and jQuery. Now, my goal is to submit the selected data IDs ...