Alter the background image of a DIV based on the selected menu item

I am working on a project that involves a div element with the class "jumbotron" which currently has a background image applied to it.

Additionally, I have a menu consisting of 6 items that I would like to interact with.

My goal is to dynamically change the background image of the jumbotron based on which menu item is clicked. Each menu item corresponds to a unique image that should replace the current background of the .jumbotron element.

Here is the basic structure of my HTML:

<div class="jumbotron">
    
</div>

    <ul class="nav nav-tabs">
        <li><a href="#" data-toggle="tab">Item 1</a></li>
        <li><a href="#" data-toggle="tab">Item 2</a></li>
        <li><a href="#" data-toggle="tab">Item 3</a></li>
        <li><a href="#" data-toggle="tab">Item 4</a></li>
        <li><a href="#" data-toggle="tab">Item 5</a></li>
        <li><a href="#" data-toggle="tab">Item 6</a></li>
    </ul>

In the CSS file, you can find the styling for the .jumbotron class:

.jumbotron {
  background-image: url(../images/item1.jpg);
}

Answer №1

Incorporate the use of css and :target to manipulate <img> elements on your website.

.jumbotron {
  width: 100%;
  height: 100%;
  display: block;
}

.jumbotron img {
  width: calc(100vw);
  height: calc(100vh);
}

.jumbotron :not(:target) {
  display: none;
}

img:target {
  display: block;
}

.nav,
.jumbotron {
  position: absolute;
}
<div class="jumbotron">
  <img src="https://lorempixel.com/400/400/cats" id="cats">
  <img src="https://lorempixel.com/400/400/sports" id="sports">
  <img src="https://lorempixel.com/400/400/animals" id="animals">
  <img src="https://lorempixel.com/400/400/nature" id="nature">
  <img src="https://lorempixel.com/400/400/abstract" id="abstract">
  <img src="https://lorempixel.com/400/400/city" id="city">
</div>

<ul class="nav nav-tabs">
  <li><a href="#cats" data-toggle="tab">Item 1</a></li>
  <li><a href="#sports" data-toggle="tab">Item 2</a></li>
  <li><a href="#animals" data-toggle="tab">Item 3</a></li>
  <li><a href="#nature" data-toggle="tab">Item 4</a></li>
  <li><a href="#abstract" data-toggle="tab">Item 5</a></li>
  <li><a href="#city" data-toggle="tab">Item 6</a></li>
</ul>

Answer №2

To display different background images on click, I suggest storing the image path in a data attribute and then accessing it when the element is clicked.

$('.nav-tabs a').on('click',function(e) {
  var bg = $(this).attr('data-bg');
  $('.jumbotron').css('background-image','url('+bg+')');
})
.jumbotron {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  z-index: -1;
  background: 0 0 no-repeat / cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="jumbotron"></div>
<ul class="nav nav-tabs">
  <li><a href="#" data-toggle="tab" data-bg="http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg">Item 1</a></li>
  <li><a href="#" data-toggle="tab" data-bg="http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg">Item 2</a></li>
  <li><a href="#" data-toggle="tab" data-bg="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg">Item 3</a></li>
</ul>

Answer №3

To change the background image when elements are clicked, simply create a click handler for each element.

If you need to access additional information about the tabs, consider using data attributes that can be easily referenced (such as for URLs).

$(".nav.nav-tabs li a").click(function(){
  $(".jumbotron").css("background-image", "url('"+$(this).data("url")+"')");
});
.jumbotron {
  background-image: url(../images/item1.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="jumbotron">    

</div>

           <ul class="nav nav-tabs"> 
                <li><a href="#" data-toggle="tab" data-url="../images/item1.jpg">Item 1</a></li>   
                <li><a href="#" data-toggle="tab" data-url="../images/item2.jpg">Item 2</a></li>
                <li><a href="#" data-toggle="tab" data-url="../images/item3.jpg">Item 3</a></li>     
                <li><a href="#" data-toggle="tab" data-url="../images/item4.jpg">Item 4</a></li>
                <li><a href="#" data-toggle="tab" data-url="../images/item5.jpg">Item 5</a></li>
                <li><a href="#" data-toggle="tab" data-url="../images/item6.jpg">Item 6</a></li>
            </ul>

Answer №4

To handle the click event for the navigation container using jQuery, I would determine which specific element was clicked and then set the background-image property for the .jumbotron element accordingly.

In simpler terms:

$('.jumbotron').click(function() {
  var target = $(this).attr('id');
  var background;
  
  switch (target) {
    case 'someId-1':
      background = 'some-url';
      break;
    case 'someId-2':
      background = 'some-url';
      break;
    case 'someId-3':
      background = 'some-url';
      break;
    case 'someId-4':
      background = 'some-url';
      break;
    case 'someId-5':
      background = 'some-url';
      break;
    case 'someId-6':
      background = 'some-url';
      break;
  }
  
  $('.jumbotron').css('background-image', 'url(' + background + ')')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="jumbotron">    

</div>

  <ul class="nav nav-tabs"> 
    <li><a href="#" id="someId-1" data-toggle="tab">Item 1</a></li>   
    <li><a href="#" id="someId-2" data-toggle="tab">Item 2</a></li>
    <li><a href="#" id="someId-3" data-toggle="tab">Item 3</a></li>     
    <li><a href="#" id="someId-4" data-toggle="tab">Item 4</a></li>
    <li><a href="#" id="someId-5" data-toggle="tab">Item 5</a></li>
    <li><a href="#" id="someId-6" data-toggle="tab">Item 6</a></li>
  </ul>

Alternatively, you could create different CSS classes for each image and toggle between them based on the clicked link.

Answer №5

Super simple. Just switch out a CSS class. You can customize the css later to adjust picture size, location, actual image, without having to modify the code.

<html>
<head>

<style>
.btnOne {
     background-image: url('obi.jpg');
}
.btnTwo {
     background-image: url('luke.jpg');
}
.picStyle {
     width: 75px;
     height: 75px;
}

</style>
</head>
<body>

<div id="btn1" onclick="changeIt ( this )">Button 1</div>
<div id="btn2" onclick="changeIt ( this )">Button 2</div>
<div id="pic" class="btnOne picStyle"></div>

<script>

function changeIt ( elem ) {
    let pic = document.getElementById ( 'pic' );
    if ( elem.id === 'btn1' ) {
        pic.classList = [ 'btnOne', 'picStyle' ];
    } else {
        pic.classList = [ 'btnTwo', 'picStyle' ];
    }
}
</script>

</body>
</html>

Answer №6

By naming your images as item1, item2, and so forth, you can execute the following code successfully:

$(document).on("click", "a[data-toggle]", function() {
  var selectedImage = $(this).text().replace(" ", "").toLowerCase();
  alert(selectedImage);
  $(".jumbotron").css("background-image", 'url(../images/' + selectedImage + '.jpg)');
})

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

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Waiting for state changes in React by using the UseState Hook

I am currently working on a function that manages video playback when clicked, and I need to set consecutive states using the useState hook. However, I want to ensure that the first state is completed before moving on to the next setState without relying ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

Manipulating Div Content with JQuery Based on Checkbox Selections

My goal is to extract content from a hidden div that contains an unordered list with specific classes and move certain list elements into placeholder divs based on checkbox values. Initially, when no checkboxes are checked, I want all list elements in the ...

Enhance your website with a customizable language selection feature using HTML and CSS

Currently, I am in the process of creating a dynamic language selection feature using HTML and CSS. Initially, this is what it looks like: https://i.stack.imgur.com/bhnaA.png Upon hovering over it, this is the effect I want to achieve: https://i.stack.i ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

What is the best way to conduct a Javascript test using Jasmine?

I'm encountering an issue with testing this JavaScript code: $("#ShootBtn").on('click', () => foo.testFunc()); var foo = { testFunc: function() { hub.server.shoot(true, username, gameCode); } } For my testing framework, ...

Struggling with React integration of AdminLTE3 sidebar treeview?

I have a requirement to create a React sidebar with a category 'Staff' that, when clicked, reveals three subordinate categories. Below is the code snippet: import React, { Component } from "react"; export default class Sidebar extends Componen ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

Creating a stunning image reveal animation using GSAP and clip-path within a React environment

When attempting to create an animation for revealing an image using GSAP and the clip-path property within a Component, I encountered an issue. The animation works perfectly when using the first clip-path value, but as soon as I switch to the other one, th ...

Wordpress users encountering a Javascript issue with Slider Revolution 5.0

Currently working on a WordPress template in LAMP environment, incorporating Revolution Slider for sliders. I have successfully created the slider and added it to the home page. However, upon checking the home page, the slider is not functioning as expec ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

What could be causing the issue with sending data via Ajax when using the `type="password"` input?

Why does sending data using ajax with input type="password" not work? The main idea is that when I fill in a password less than 6 characters, it should display Password minimum 6 characters I tested this code and found that it was not working. So, I edit ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

Retrieving the previous value using JQuery's onChange event

Is there a way to retrieve the initial quantity value before it is changed with the onChange function in this code snippet? I'm encountering issues with the CSS while using this setup for an input box. You can view the problematic CSS here. Updating ...

Trouble with displaying canvas images in imageDraw() function

I'm having trouble with my Imagedraw() method when trying to obtain image data using toDataURL(). var video = document.getElementById('media-video'); var videoCurrentTime = document.getElementById('media-video').currentTime; var ...

Ways to retrieve property value from a component in Vue.js 2.0

I am currently working with a specific component that allows for date selection: <template> <div class="animated fadeIn"> <div class="col-sm-6 col-lg-6"> <datepicker class="form-control" :value="config.state.fromDate" ...

What is the reason for encountering an error when attempting to use a let variable in a new block before reassigning it

Check out this document here where I attempt to explain a coding scenario: // declare variables const x = 1; let y = 2; var z = 3; console.log(`Global scope - x, y, z: ${x}, ${y}, ${z}`); if (true) { console.log(`A new block scope - x, y, z: ${x}, $ ...

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

Utilizing Bootstrap divs for multiline display in Yii2 platform

Currently, I am utilizing a list in Bootstrap CSS which is responsive and beneficial. However, I am faced with the challenge of creating a notification list with lengthy text akin to that on Facebook. My query pertains to the technique required to make th ...