When it comes to identifying a click outside of an element, the Jquery or Javascript function may encounter some challenges specifically with Internet Explorer

After reviewing various solutions online, I noticed that they all function properly on Chrome and Firefox but encounter issues with Internet Explorer when interacting with an SVG. For instance, consider the following code snippet:

$(document).on("click",(e) => {
    this._handleDocumentClick(e);
});

_handleDocumentClick(e) { 
    let container = $(".myClass");

    if (container.has(e.target).length === 0) { 
        alert('clicked outside');
    }
}

In IE, this code fails to work correctly when clicking on an SVG element (and possibly an image as well). Despite the SVG being located inside my designated container, the script incorrectly registers it as an external click!

When printing e.target, the following element (and its length) is displayed:

https://i.stack.imgur.com/dACze.png

Any suggestions or insights on how to resolve this issue?

Answer №1

Take a unique approach by utilizing jQuery's .closest() method to check if the target element is a child of the container:

var $container = $('.target');

$('body').on('click', function(evt) {
  var $target = $(evt.target);

  if ( $target.closest($container).length ) { 
    console.log('❌ click inside');
  }
  else {
    console.log('✅ click outside');
  }

});

You can view a demo of this in action, compatible with IE9+ http://jsbin.com/qoqume/edit?html,js,console,output

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

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Encountering a difficulty in sending data to the server through ajax with Cordova

I am currently working on a Phonegap Cordova project and I'm trying to send data to the server using AJAX but I'm encountering an error. Here is an example of my code: $(document).ready(function() { $('#frm').submit(function() ...

The Angular controller fails to execute upon startup in the Ionic app

As a newbie to the Ionic Mobile Framework and Angular JS, I'm working on a login page for the first time. My goal is to navigate to the homepage only if the session has not expired when the login page launches. If the session has expired, then it shou ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

What is the best way to retrieve data from a POST request?

I am attempting to post data from the same site and create a new order when the submit button is clicked. However, I am not receiving any information in my req.body, leading me to suspect that there may be an issue with my ejs file. Any feedback on this ma ...

What is the proper way to define the type for a functional React component by using object destructuring on props?

As I continue to learn TypeScript and work on declaring advanced types, I am faced with converting my CRA project to TypeScript. Within this project, I have a component that closely resembles examples from react-router-dom, but I have not come across any T ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

The socket.on event appears to be triggering multiple times with each response

After successfully setting the socket.emit event upon commenting, I encountered an issue when binding the sockets.on event. It seems to be firing multiple times. $(document).on('click', '#comment_button', function() { $.ajax({ ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

The JQuery datepicker fails to display the current date

I am experiencing an issue with the datepicker on my webpage. While it is working correctly, the default date being displayed is '01/01/2001' instead of '11/23/2012', as I intended. Here is the jquery code I am using: $(":inpu ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...

Alter the class of the div element every three seconds

Greetings, I trust everyone is doing well. I am in need of some assistance from your brilliant minds. I have a circular div along with three CSS classes, and my objective is to switch the div's class and update the label text every 3 seconds. Any insi ...

The Node.js server delivers a different object to the client

I'm facing an issue while trying to send an object from the client to a Node.js server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, // application/x-www-form-urlencoded; cha ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Using NicEdit for uploading to your personal server

I'm having trouble uploading images using the NicEdit WYSIWYG editor on my own server. When I click on the upload image button, it redirects me to another site where I can upload the image: imgur dot com You can find a demo of this here: However, I ...

The requested API endpoint for retrieving the name could not be found on the Express

Struggling to configure the restful API for my express app. Below is my app.js code: var express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'); rout ...

Locating the Active Object's Coordinates in fabric.js

When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...