Switching the background image of a div by clicking on a different div

To start, you can locate all of my code right here.

http://jsfiddle.net/yfukm8kh/1/

The issue I'm encountering pertains to the following section.

var changePic = function (direction, id, array) {

    var intID = parseInt(id);
    var intDir = parseInt(direction);
    if (intID > 0) {
        intID = intID + intDir;
        currentID = intID;
        alert(array[intID].link);
        $('#lightbox').css("background-image", array[intID].link);
    } else if (intID == 0 && intDir == 1) {
        intID = intID + intDir;
        currentID = intID;
        alert(array[intID].link);
        $('#lightbox').css("background-image", array[intID].link);
    }
};

The goal for this function is to modify the background-image of the div id=lightbox to one specified in the provided array.

However, when clicking on the sidebar, it seems that the entire <div id=lightbox> is being removed as though the click was directed at the div itself rather than the sidebar. Nonetheless, upon inserting an alert within the function, it confirms that the event was triggered and some code within the function executed.

I suspect that clicking on the sidebar triggers two events - one for changing the background-image and another for removing the lightbox element again.

Is there a way to prevent the underlying div from responding to the click?

Furthermore, please feel free to correct me if I've misused any terms or violated proper posting etiquette. As a newcomer, any guidance from seasoned users would be greatly appreciated.

Thank you very much.

Answer №1

To prevent event propagation in the sidebar events, you need to use stopPropagation().

Using event.stopPropagation():

This function stops the event from bubbling up through the DOM tree, preventing any parent handlers from being notified of the event.

Code Example:

$(document).on('click', '#leftBar', function (event) {
        event.stopPropagation();
        changePic(-1, currentID, activeArray);
    });

    $(document).on('click', '#rightBar', function (event) {
        event.stopPropagation();
        changePic(1, currentID, activeArray);
    });

Check out the Updated Fiddle:

http://jsfiddle.net/yfukm8kh/3/

If you want to learn more about Event Bubbling and Propagation, make sure to read up on it!

Answer №2

Are you looking to target specifically the #lightbox element and not its contents?
You can achieve this by using the following code:

$('body > #lightbox').css("background-image", array[intID].link);

Answer №3

  • To avoid triggering the click event for #lightbox, you can simply include return false; in the handlers for the right and left bars.
  • I made sure to move the click handler for #lightbox out of the click handler for .singapore to prevent multiple instances of this handler being added.

Check out the updated fiddle here.

$(document).on('click', '#leftBar', function () {
    changePic(-1, currentID, activeArray);
    return false;
});

$(document).on('click', '#rightBar', function () {
    changePic(1, currentID, activeArray);
    return false;
});

$('.singapore').click(function () {
    currentID = event.target.id;
    openThumbnail(singaporeArray, currentID);
});

$(document).on('click', '#lightbox', function () {
    $(this).remove();
});

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 method to load only specific element contents using .load() rather than the entire web page?

I have a web page that allows users to add, edit, and update different sections. These segments are stored on an external page, and I use the jquery .load() function to achieve this functionality. However, I am facing some concerns regarding this process: ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...

Is there a way to override the padding of a container?

Working with Wordpress for the first time has been quite a challenge. Adjusting to everything is causing me some major headaches. So, I've got this container div and added a lazy 10px padding. However, for the theme I'm attempting to develop, I ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

How to center a text box within a div using CSS

Looking for equal margins on top and bottom? Here's how to achieve it: If you have a container div like this: <div id="search"> <input id="txtSearch" type="txt"> </div> Your CSS should look something like this: #search{ m ...

What are effective ways to design a dialogue or conversation with CSS styling?

Looking to create a design similar to this one, but unsure of the terminology: I am open to different approaches for the layout, but possibly something along these lines: https://codepen.io/nachocab/pen/LaBwzw .container { width: 600px; } .speaker ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Implementing a sorting mechanism for ajax data retrieval

Currently, I am using the code below to save HTML created with jQuery in a database and retrieve it later: $('div[read]').each(function(){ var kelas = $(this).attr('kelas'); $.post('admin.php',{kelas:kelas,id:id},func ...

Implementing a gradient effect on a specific image element within an HTML canvas with the help of jQuery

Currently, I'm working on an HTML canvas project where users can drop images onto the canvas. I am looking to implement a linear gradient effect specifically on the selected portion of the image. My goal is to allow users to use their mouse to select ...

What is the best way to center this image horizontally within its variable-sized parent container?

I am currently working on a webpage that has a responsive design. The page features a list of products, with the product listing adjusting in size as the page width changes. My goal is to center the product image within its container, ensuring that the i ...

Implement a counter in a JavaScript table, initializing it to zero

I have successfully written my code, but there is one issue. The first row is starting with the number one instead of zero. I'm looking for suggestions on how to start from zero. Any help would be greatly appreciated. Thanks! <script> var tabl ...

Ensuring Stringency in JQuery's '$' Selector

I have a specific data attribute within the div element that is displayed in the HTML. <div my-custom-attrib="1".../> <div my-custom-sttrib="2"...> Now, in JQuery, I am attempting to filter between the div elements based on the value of the c ...

Container element refusing to grow in size while the footer remains fixed on the screen

Description: I recently encountered an issue with the layout of my website. I have a main content div (#main) and a container div (.display), which should expand automatically with content to push the footer down. Initially, I struggled to get this workin ...

Unleash the power of jQuery.keypress for lightning-fast text processing

Looking to customize the keypress event for real-time text transformation as you type. Here's what I've tried: field.keypress(function(e){ field.val(function(i, val){ return val.toUpperCase(); }); return false; }); The input ...

jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for ...

Assigning a price to a list of pizza options within a dropdown menu

//The goal is to assign a numerical price to each pizza in the array. We must maintain the structure of the array within the select form. Next, we need to display it in another PHP file, how do we retrieve the values? <fieldset> ...

Battle of Cookies and User Preferences: Who Will Prevail?

Recently, I encountered a challenge while developing an ecommerce site. After facing numerous issues, I believe I may have finally found a solution. (For more details on the problem and my question, click here) The expected scenario: Users checkout and p ...

How can we stop a form from being submitted when the input field is

Similar Question: How to prevent submitting the HTML form’s input field value if it empty <?php include '../core/init.php'; if(isset($_POST['nt']) && isset($_POST['ntb'])){ mysql_query("INSERT INTO `pos ...

Having trouble with submitting the jQuery form

I have written a script to submit a form after validation and receive the values in a PHP file using $_POST. However, I am not able to retrieve the values in the PHP file. When I try to echo the values, it shows up as blank. Can someone please guide me a ...