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

Utilize Custom Field to incorporate background videos from websites like Youtube or Vimeo into your content

I've been working on implementing a video background for my website. I came up with a custom code to embed URL links from Youtube and Vimeo using "oEmbed". The process is functioning well, but I'm facing some challenges in setting the background ...

Could somebody provide clarification on the functions being called in the Angular Test Code, specifically evaluate() and dragAndDrop()?

Exploring the drag and drop functionality of an angular-Gridster application using Protractor with a test code. I have some questions about the functions being used in the code snippet below. Can someone clarify the purpose of evaluate() - the API definit ...

Error encountered: The use of 'import' and 'export' is limited to 'sourceType: module' when attempting to install Tweakpane

I am currently learning JavaScript and have been following a course on Domestika that requires me to install the Tweakpane package. I usually use Git Bash for installing packages, and I have successfully installed others this way before. Here is the proces ...

How can one create custom JavaScript UI controls for a UWP application?

I am currently working on a UWP application and I am looking to incorporate JavaScript HTML5 based UI components. Is there a method to integrate this UI into a UWP application? My UI is completely developed using JavaScript, jQuery, CSS, and HTML5, and I w ...

What is the best way to integrate an AJAX callback into the stop condition of a `do while` loop?

Take a look at the code snippet below: let count = 0; do { $.ajax({ type: "POST", url: someurl, dataType: 'xml', data: xmlString, success: function(xml) { count++; } } while(co ...

The body's width is more compact compared to one of my containers in HTML/CSS

After completing my code for a beginner's HTML/CSS project, I realized that the main parent container holding two smaller containers needed to be set at specific widths. The two inner containers had to be exactly 650px and 270px wide, while the main p ...

Error: The AJAX request encountered an unexpected token in the JSON response

I am working with the following code snippet: $.ajax({ dataType: 'text', url: '/_/js/answers.json', type: "GET", success: function (data) { alert(data); ...

What value does a variable have by default when assigned to the ko.observable() function?

I am in the process of learning KnockoutJS and I have implemented code for folder navigation in a webmail client. In the view code, there is a comparison being made to check if the reference variable $data and $root.chosenFolderId() point to the same memor ...

Transition effortlessly between web pages with subtle fading effects

I want to implement smooth page transition effects between two web domains: mcpixel.co.uk/new and mcpaper.co.uk. I am the owner of both domains. When a link in the header is clicked, I'd like the page to fade transition to the new page without any whi ...

Utilizing ReactJS: Expanding my knowledge of updating array object indexes dynamically when removing elements

Currently, I am in the process of creating a to-do list application to improve my skills in working with ReactJS. This is how my initial state looks like: const [listx, setlistx] = useState( [ {id: 0, flavor: 'strawberry', ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

The trim() method in Vue.JS does not properly handle trimming a passed string

I've been attempting to eliminate white space from a property of one of the returned objects using the .trim() function, but it's not working as expected. Even after trying JavaScript functions like .replace(/\s/g,''), the issue p ...

What is the best way to distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

The REST API endpoint links for Timestamp are displaying a 404 error message indicating they cannot be

After recently diving into backend development, I ran some tests locally using Postman and localhost which seemed to work perfectly. However, upon uploading my code to GitHub, I encountered a 404 error when clicking on the API endpoint hyperlinks from inde ...

Express server experiencing a conflict with authentication sessions

Currently testing out a library found on this link and encountering a frustrating issue related to potential conflicts in cookie or header authentication. Upon logging into one account, everything runs smoothly. However, attempting to log into a different ...

The Bootstrap carousel comes with a brilliant feature! Conceal those 'previous' and 'next' buttons when you reach the first and last slide. However, it seems like the 'slide' event is not functioning as

I have implemented a standard Bootstrap carousel on my website: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data- ...

Error encountered when running the production build server for android in Meteor: TypeError - Unable to access property 'slice' of null

Here's a demo I'm working on: https://github.com/pc-magas/pupAndroidDemo I'm trying to build this demo for Android. I've already installed the Android SDK and configured the necessary environmental parameters. Following the instructio ...

Avoid matching the regular expression

Currently, I am utilizing the regular expression /\s*?left:\s*?-?\d+\.?\d*px;/im to search for instances like: left: 100.5px;. An issue that I am encountering is that it also detects margin-left: 100px; or padding-left.... My obje ...

Hover over the image with some padding placed around it to see

I am struggling to figure out how to add padding to my image when hovering over it with Onmouseover. I have tried multiple solutions but none seem to be working. Here is the original code: <img src='/wp-content/uploads/2015/04/img-white.png' ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...