HTML - one div's child element takes precedence over another div

My HTML page features two consecutive divs. The first div contains a child span that has a relative position, causing it to overlap the second div.

I have implemented click events for both divs. However, when I click on the span that overlaps the second div, it triggers the click event for the first div instead of the intended second div.

Is there a way to ensure that clicking on the overlapping part of the span triggers the click event for the second div?


                function div1Clicked() {
                    alert('div 1 clicked');
                }

                function div2Clicked() {
                    alert('div 2 clicked');
                }
            

                #div1 {
                  border: 1px solid gainsboro;
                  height: 100px;
                  width: 13%;
                  background: red;
                  display: inline;
                  float: left;
                }

                #div1 span {
                  width: 316px;
                  height: 30px;
                  background: green;
                  float: left;
                  margin-top: 39px;
                  position: relative;
                }

                #div2 {
                  border: 1px solid gainsboro;
                  height: 100px;
                  width: 13%;
                  background: red;
                  display: inherit;
                  float: left;
                }
            

                <div onclick="div1Clicked()" id="div1">
                  <span>
                    </span>
                </div>

                <div onclick="div2Clicked()" id="div2">
                  <div>
                  </div>
                </div>
            

Answer №1

If you want to avoid using a hover state on the child span, here's a simple solution. Although it may differ slightly from your current HTML structure, it can easily be converted to fit your needs. Unfortunately, I don't have time to do that right now.

One way to achieve this is by adding :after pseudo-elements to two divs with a higher z-index. These pseudo-elements will overlay the span and serve as trigger areas for your JavaScript functions. The CSS might look a bit unusual due to BEM methodology, but your JavaScript triggers should work smoothly. If you're not comfortable with using console logs, feel free to use alert() for debugging purposes instead.

Check out the DEMO

<div class="block">
  <div class="block__column block__column--left js-action-1"></div>
  <div class="block__column block__column--right js-action-2"></div>

   <div class="block__description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil, voluptas!</div>
</div>


.block {
  display: flex;
  position: relative;
}

.block__column {
  width: 50%;
  height: 20rem;
  position: relative;
}

.block__column:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
}

.block__column:hover {
  cursor: pointer;
}

.block__column--left {
  background-color: deepskyblue;
}

.block__column--right {
  background-color: deeppink;
}

.block__description {
  position: absolute;
  top: 50%;
  left: 2rem;
  right: 2rem;
  background-color: white;
}


$('.js-action-1').on('click', function() {
 console.log('clicked the left column');
});

$('.js-action-2').on('click', function() {
 console.log('clicked the right column');
});

Answer №2

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div onclick="div1Clicked()" id="div1" style="
    border: 1px solid gainsboro;
    height: 100px;
    width: 13%;
    background: red;
    display: inline;
    float: left;
">
<span style="
    width: 316px;
    height: 30px;
    background: green;
    float: left;
    margin-top: 39px;
    position: relative;
">
</span>
</div>

<div onclick="div2Clicked()" id="div2" style="
    border: 1px solid gainsboro;
    height: 100px;
    width: 13%;
    background: red;
    display: inherit;
    float: left;
">
<div>
</div></div>
<script>
function div1Clicked(){
if($("div:first").width() < event.offsetX)
div2Clicked()
else
alert('div 1 clicked');
}

function div2Clicked(){
alert('div 2 clicked');
}
</script>
</body></html>

When clicking on the span element triggers the parent element's (div1) event, it does not produce the correct output. However, under certain conditions, you can still obtain the expected output. Please see the following code snippet for reference:

function div1Clicked(){
if($("div:first").width() < event.offsetX)
div2Clicked()
else
alert('div 1 clicked');
}

Answer №3

When the green span is clicked, it triggers the click event of div1 even if it overlaps div2. To ensure that the div1 click event is still fired, consider using the onclick event of the green span instead. This will maintain the functionality of firing the div1 click event.

<html><head></head>
<body>
<div onclick="div1Clicked()" id="div1" style="
    border: 1px solid gainsboro;
    height: 100px;
    width: 13%;
    background: red;
    display: inline;
    float: left;
">
<span style="
    width: 316px;
    height: 30px;
    background: green;
    float: left;
    margin-top: 39px;
    position: relative;
" onclick="spanClicked()">
</span>
</div>

<div onclick="div2Clicked()" id="div2" style="
    border: 1px solid gainsboro;
    height: 100px;
    width: 13%;
    background: red;
    display: inherit;
    float: left;
">
<div>
</div></div>
<script>
function div1Clicked(){
alert('div 1 clicked');
}

function spanClicked(){
alert('span clicked');
}

function div2Clicked(){
alert('div 2 clicked');
}
</script>
</body></html>

Answer №4

If you find that click-events on the span element are unnecessary, one solution is to use `pointer-events: none` in the CSS for the span. This will prevent any clicks on the span from registering.

function div1Clicked() {
  alert('div 1 clicked');
}

function div2Clicked() {
  alert('div 2 clicked');
}
#div1 {
  border: 1px solid gainsboro;
  height: 100px;
  width: 13%;
  background: red;
  display: inline;
  float: left;
}

#div1 span {
  width: 316px;
  height: 30px;
  background: green;
  float: left;
  margin-top: 39px;
  position: relative;
  pointer-events: none;  /*This will make the span click-through*/
}

#div2 {
  border: 1px solid gainsboro;
  height: 100px;
  width: 13%;
  background: red;
  display: inherit;
  float: left;
}
<body>
  <div onclick="div1Clicked()" id="div1">
    <span></span>
  </div>
  <div onclick="div2Clicked()" id="div2">
    <div>
    </div>
  </div>

Answer №5

Check out this example below...

$('.first,.second').click(function(){
alert($(this).attr('class'))
})
.first{
    width:200px;
    height:300px;
    background-color:red;
    display:inline-block;
    float:left;
    position:relative;
}
span{
    position:absolute;
    left: 30%;
top: 30%;
}
.first:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
}
.second:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 99;
}
.second{
    width:200px;
    height:300px;
    background-color:green;
    display:inline-block;
    position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="first">
      
    </div>
    <div class='second'>
    </div>
     <span>Hello World....</span>
</body>

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

Create a fresh array by merging two existing arrays while maintaining the order of values

I have a pair of arrays: array one: ( [0] => 2 [1] => 5 ) array two: ( [0] => Sentry [1] => Maxima ) and I'm attempting to create a new array that resembles the following new array: ( ["Sentry"] => 2 ["Maxima ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Issue encountered with JavaScript AJAX involving a Cross Domain ASMX Web Service JSONP Request

I have been working on a local web service that I believe fits the criteria for making cross-domain JavaScript calls to access external data within Dynamics CRM. However, I am facing some challenges in creating the JavaScript AJAX code needed to connect wi ...

Executing a php function upon onchange event triggered by CKEditor

My task involves invoking a PHP function when I suspect it is being triggered by an ajax call. Utilizing ckeditor, I aim to detect any keyboard activity and believe that using onchange will serve this purpose. Subsequently, I plan to execute a function t ...

WebDriver patiently anticipating the completion of page loading amidst ongoing AJAX calls in the background

During my testing of a web application, I encountered a scenario where one of the header elements needed to be refreshed every 5 seconds. This header element was responsible for updating all users with a message whenever a Quote/Policy was issued by anyone ...

Issue with jQuery delay() causing animation disruptions

I've implemented a drop-down menu that functions smoothly, but I'd like to enhance it by making the drop-down stay visible for an additional 500ms after the user hovers out of the box. My attempt at using .delay(500) led to the animation getting ...

What Occurs to Processed Messages in Azure Functions if Result is Not Output?

I have created an Azure function that is connected to the messaging endpoint of an IoT Hub in order to trigger the function for all incoming messages. The main purpose of this function is to decompress previously compressed messages using GZIP before they ...

Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thou ...

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

Establishing a pre-defined value for a filter that impacts an HTML table upon the page's initialization

table: <input id="weekFilter" type="text" name="myInputSearches" placeholder="Week..." style="margin-top:4px"> <label class="noResults" align="right" style="display:none; color:red"><b><i>No Match Found</i></b></labe ...

Dealing with AngularJS: Issue arises when attempting to inject $modal into a controller nested within a directive

Our team has implemented a custom directive that wraps around a checkbox and utilizes transclusion to inject content into it. Here is an example of the setup: somecheckbox.js angular.module('namespace.directives') .directive('someCheckbox& ...

Node.js based simplistic static HTML web server

I'm looking to create a basic server for serving local HTML and JS files while working on development projects. I attempted to use a node app with express to respond with the page based on the URL, but unfortunately had no success. Here's my cod ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Step-by-step guide on invoking a recursive function asynchronously in JavaScript

As I delved into the realm of creating a unique Omegle clone using Node.js and Socket.io for educational purposes, I encountered a challenge that has left me scratching my head. The socket ID of clients along with their interests are stored in an array of ...

The gauge created dynamically using the justgage plugin does not display the value

I am currently experimenting with dynamically adding gauges, and although they are displayed on the screen, the values being shown are incorrect. Even when the graph indicates a different value, it still displays 0. These gauges are triggered by an onclick ...

The persistent space between the navbar and the index page remains despite the suggested fixes provided

There appears to be a discrepancy between the navigation bar and the rest of the page. Despite my efforts to adjust margins, I haven't been able to resolve it. The system is prompting me for more details before posting this question, but I'm unsu ...

Centered Tailwind CSS logo design

Here is my current fiddle: https://jsfiddle.net/w5c36epd/ Upon close inspection, you may notice that the logo is not properly centered. I have experiment with various flexbox options such as: <div class="flex-shrink-0 justify-center"> ...

Clicking on a JQuery element triggers an AJAX function, although the outcome is not aligned with the intended

Instead of using a fiddle for this task, I decided to work on it online since my knowledge of fiddles is limited. However, after multiple attempts and hours spent rewriting the code, I still can't get it right. The issue at hand requires that when cl ...

Arranging grid elements in Material-UI

Currently, I am in the process of transforming a JavaFx window into a web application using React.js & Material Ui. The goal is to replicate the appearance and functionality of the original JavaFx application as closely as possible. The layout of the wind ...