How about "Switching Background Images Using a Click Trigger"?

I have a single web page with three different tabs. By clicking on each tab, the text displayed changes accordingly. I am looking to add three separate images for each tab so that when a user clicks on a specific tab, the image associated with it also changes. You can view the theme's link here:

Below is the JavaScript code snippet that handles the text change functionality upon tab clicks.

//Swap Titles

jQuery(document).on('click','.current-directory',function(){    
        jQuery(this).parents('ul').find('li').removeClass('active');
        jQuery(this).addClass('active');
        var dir_name    = jQuery(this).data('dir_name');
        var id  = jQuery(this).data('id');
        jQuery(this).parents('.tg-banner-content').find('em.current_directory').html(dir_name);

        if( Z_Editor.elements[id] ) {
            var load_subcategories = wp.template( 'load-subcategories' );
            var data = [];
            data['childrens']    = Z_Editor.elements[id];
            data['parent']      = dir_name;
            var _options    = load_subcategories(data);
            jQuery( '.subcats' ).html(_options);
        }

    });

    //Prepare Subcategories
    jQuery(document).on('change','.directory_type', function (event) {
        var id        = jQuery('option:selected', this).attr('id');     
        var dir_name    = jQuery(this).find(':selected').data('dir_name');

        if( jQuery( '.dynamic-title' ).length ){
            jQuery( '.dynamic-title' ).html(dir_name);
        }

        if( Z_Editor.elements[id] ) {
            var load_subcategories = wp.template( 'load-subcategories' );
            var data = [];
            data['childrens']    = Z_Editor.elements[id];
            data['parent']      = dir_name;
            var _options    = load_subcategories(data);
            jQuery( '.subcats' ).html(_options);
        }
    });

The following CSS code has been customized in an attempt to add multiple background images instead of just one static image. However, only one image is being added and does not change dynamically as desired.

.tg-homebanner{position: relative;}
.tg-homebanner figure{
    width: 100%;
    float: left;
    margin: 0;
    z-index: 1;
    position: relative;
}
...
/* Additional CSS styles go here */

.show-search i{
    position: relative;
    top: 50%;
}

Recent modifications were made by updating the CSS as shown below:

.tg-banner-content{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    background: url('URL OF MY IMAGE') center center no-repeat;
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-image:linear-gradient(to bottom right,#002f4b,#dc20000);
    opacity: 1;
}

Despite the changes above, only one background image is being displayed without changing with each click on the tabs.

Answer №1

Learn how to create a button click event that changes your background image using JavaScript with this sample code snippet:

    <script>
function changeBackground() {
    document.body.style.background = "#000000 url('img.png') no-repeat right top";
}
</script> 

Answer №2

Check out the following complete code!

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#tabs" ).tabs();
    $( "#tabs_head li" ).on("click",function(index, element) {
        var tabid=$(this).attr("data-tab");
        var tabimag=$(this).attr("data-src");
        //alert(tabimag)
        $("#"+tabid).css('background-image','url(' + tabimag + ')')

    });
  } );
  </script>
</head>
<body>

<div id="tabs">
  <ul id="tabs_head">
    <li data-tab="tabs-1" data-src="http://www.mssinfotech.com/uploads/slider/8e5a16689b28b64d49b5178fa0bd78c3.jpg"><a href="#tabs-1">Nunc tincidunt</a></li>
    <li data-tab="tabs-2" data-src="http://www.mssinfotech.com/uploads/slider/ac1549a0ba88a7d802e83ddbce7622e6.jpg"><a href="#tabs-2">Proin dolor</a></li>
    <li data-tab="tabs-3" data-src="http://www.mssinfotech.com/uploads/slider/c6693db9f27305653009f21affcb261d.png"><a href="#tabs-3">Aenean lacinia</a></li>
  </ul>
  <div id="tabs-1">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.</p>
  </div>
  <div id="tabs-2">
    <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc.</p>
  </div>
  <div id="tabs-3">
    <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem.</p>
    <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus.</p>
  </div>
</div>

</body>
</html>

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

What is the best way to access the complete information from a kendo ui dropdown menu?

I am attempting to retrieve all the data from a kendo dropdown list. I have created the dropdown with the following code: $("#dropDownList").kendoDropDownList({ dataTextField: "field", autoBind: true, dataSource: { transport: { ...

What could be causing my line-clamp to malfunction when using a fixed height in the Safari browser?

I have a problem with the design of my episode list on mobile devices. The list has a fixed height, and I am using the line-clamp-2 property for the episode titles that exceed two lines. While everything looks fine on my PC and even when using Dev Tools t ...

Enhance the jQuery output by adding additional parameters

After executing a jQuery function, I have obtained the following output: users => "1", "2", "3", "4" Now, I have an array of data that reads '4', '3', '4', '4'. I am looking to add another piece of data as coun ...

The clash between the position:fixed and overflow:visible styles in CSS

I'm working on a webpage layout that includes an image positioned on the right side of the page. I want to create horizontal scroll bars when the browser window is resized, so I added the overflow: visible property. Additionally, I want the image to b ...

The result of the AJAX GET request is not defined

Despite seeing the response data in the browser's developer tool network tab, my AJAX GET response is showing as undefined. The AJAX request code I am using is as follows: $.ajax({ url: "https://api.leroymerlin.it/product-api-v2/v1/allStoreS ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

The layout of the table is not formatted in a single continuous line

I recently implemented the material-ui table and noticed that the header has a multiline break space. I am looking for a way to make it display in a single line instead. Is there any solution for achieving this using material UI or CSS? Feel free to chec ...

How to create a clickable link that functions as a file upload button

I am working on a project where I need to create a link that acts as a file input when clicked. Here is the code for the link: <a id="upload-file">Upload your photo</a> Is there a way to make this link function as a browse file input? Any ...

Having four videos displayed on one webpage can cause the browser to function at a slower

I have videos that are around 30 seconds long and 15mbs. I'm wondering if it's feasible to include them on a page or if I should opt for cover images instead. I would like to use the video as a separator similar to the design showcased at Does a ...

Why is my ASP.NET checkbox losing its value after postback because of a JavaScript/jQuery array?

I'm facing an issue with a simple asp:RadioButtonList nested inside a form tag where it's not retaining its value on postback. Here's the code snippet: <form runat="server"> <div class="Form"> <span class="FirstField"> ...

Saving form data with a tinymce textarea, radio button, and checkbox to the database

My form contains multiple textarea fields, radio buttons, checkboxes, and a select input. Initially, I was able to submit the form using PHP without any issues. However, when I integrated TinyMCE with one of the textareas, I had to introduce JavaScript to ...

Connecting different jQuery methods to create a chain

From my understanding of jQuery chaining, the first method in the list must complete before the next method executes. Here is an example: $.fn.reportZebraStriper = function(options) { console.log('reportZebraStriper()'); return true; } ...

Script for iterating and replacing values

$(".IT_Badge").each(function(){ var badges = $(".IT_Badge").val().trim().split(","); for (c = 0; badges.length > c; c++) { currentBadge = badges[c]; $this.find('.IT_Badge').replaceWith($("<img/>").attr("src", &ap ...

Preserve proportions while resizing the browser window

I needed my code to ensure that the images keep their aspect ratio regardless of the screen size or if the user resizes their browser instead of viewing it full screen. I have some code in place, but I'm unsure how to maintain the current effects of ...

Identifying flags that do not actually exist in flag-icon-css library

Please take a moment to review the code snippet provided. I have created a Datatable that contains countries along with their country codes. Within my code, I am generating HTML to display flag icons using the format flag-icon-COUNTRYCODE. However, some ...

Tips for avoiding word fragmentation in <pre> code blocks

pre { white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ overflo ...

Having trouble customizing the appearance of the active state for the close button in jQueryUI's Dialog

I am trying to customize the active state of the close button in the title bar of a jqueryUI dialog. While I have successfully styled its normal and hover states, the active state doesn't seem to respond as expected. Could there be a feature in the p ...

The background image on my link bar is inexplicably not appearing

I've been trying to solve this issue for hours and I'm at a loss. Initially, the background image was displaying correctly, but now it's not working. HTML: <head> <link type="text/css" rel="stylesheet" href="css/normalize.css" ...

The issue with Ng-Zorro select preventing the display of selected items when using NgModel

I am currently working with Ng-Zorro's multiple select feature, housed in a drawer. While populating the select element with a list of available options and pre-selected items upon opening the drawer, I've encountered an issue where the already c ...

Having trouble with my ajax success function, could use some assistance please

Having issues passing values from an AJAX request to a PHP file. The error function seems to be working, but I can't figure out what's wrong with my code. Here is what I have: <script> function test(){ //alert("hello"); var myD ...