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

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked. Bel ...

The URL's ajax GET request is timing out despite it working fine in browsers and CURL

I came across a question similar to mine, but unfortunately it does not have an accepted answer. My issue lies with the ajax request timing out. Strangely enough, when I make a `GET` request using the browser or `curl` on the same URL, everything works pe ...

The main menu items in jQuery do not display the child sub menu upon clicking

I'm currently in the process of creating a unique mobile menu for my Wordpress website, but I'm facing some challenges when it comes to displaying and hiding the sub-menu items. I've assigned the class name .menu-item-has-children as my sele ...

Converting php array submitted from a form using ajax

I have a form on my website that collects user input and sends it to an email address using php. The form includes a checkbox input where users can select multiple options, which are then stored in an array. However, when the form is submitted, the email r ...

Sending a different name for the jQuery parameter

I'm looking to select CSS settings based on the presence of a data tag. What would be the correct approach for this? var datadirection = 'left'; //default direction if( $(this).attr('data-right') ){ datadirection = 'righ ...

Mapping a JavaScript object to an MVC model: A comprehensive guide

I have a JavaScript object as shown below: $scope.docPropIdentityModel = { Owner: {OwnerID:"", OwnerName: ""}, }; I need to send this object to my MVC controller using an AJAX call. Let's say the controller looks like this: controll ...

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

Can someone please provide me with tips on how to prevent jQuery validate from automatically validating?

Currently, I have implemented an onblur script for a textbox that converts user input into a date. Despite utilizing the jQuery validate plugin for validation purposes, a challenge arises where the input is not considered valid until it has been parsed. Th ...

Transfer the value of a variable within the local scope to the dragstart event handler during the dynamic generation of an input element

After going through several similar questions, I couldn't find a solution that applies to my specific case. Here is the loop I am working with: $.each(data.modules, function(i, field) { let $li = $(`<li><div> Name: ${field.name}</div& ...

Exponential calculator in Javascript

I'm working on a basic calculator project using html5, css3 and javascript. However, I've run into an issue with the exponent button not functioning properly. Here's my code snippet: <html> <head> <meta charset = "utf-8" ...

How to make a line stand out in an HTML table using <td> tag: **Bold a

I have written the code below to create a table, and I only want the text XYZ to be bold and all other text to remain unbold within the < td > tag. However, when I implemented this code, the entire < td > content became bold. I would prefer not ...

Calendar: Display upcoming dates within the next week starting from the current week

Hey there! I have a calendar that includes next and previous buttons. When the user clicks on the next button, the schedule for the upcoming week will be displayed. However, if the user clicks again, nothing happens. My goal is to only show dates for the n ...

Hover over the div to center an SVG inside it

Simply put, I am working on a design where a gradient bar moves above a specific element when hovered, creating a visual effect of a triangle. I am now looking for a way to center an SVG inside the element on hover, to create a similar triangular gradient ...

Is it possible to alter the background color once the content of an input field has been modified?

I am working with an angular reactive form and I want to dynamically change the background color of all input fields when their value is changed. Some of these input fields are pre-populated and not required. I came across a potential solution on Stack Ove ...

Guide to setting up a custom js file in Laravel admin template

Currently working with Laravel 5.8 and utilizing the laravel-admin Template for administrative purposes. There are times when I require custom JavaScript and CSS files specifically for certain admin controllers. How can I include these JS and CSS in lara ...

The issue of Basic Bootstrap 5 Modal triggering twice is causing a frustrating experience

My modal is almost working perfectly - it changes content based on the clicked image, but it is triggering twice in the backend and I can't figure out why! I followed Bootstrap's documentation for this, so I'm unsure where the issue lies. Al ...

Using jQuery AJAX enforces the use of HTTPS

Here is the current setup: Using jquery version 2.1.1 Employing nodejs (not a crucial factor) Making requests over https The issue at hand: When using $.getJSON() and $.get(), the URL requested appears as "". Despite confirming the correctness of the UR ...

What is the reason that my link to test.xls is functioning properly but the one to the .txt file is not working?

I am facing an issue with downloading files from a folder named Test. In this folder, I have various file types such as .xls, .txt, and .doc files. Within the html code, I have specified download links for these files: <p> <a href="../../Test/St ...

The Everyday Explanation of Same Origin Policy

Could anyone simplify the concept of the Same Origin Policy for me? I've come across various explanations but I'm in search of one that a child can easily understand. I found this link to be quite helpful. Is there anyone who can provide further ...