How to access event.target in Internet Explorer 8 with unobtrusive Javascript

Here is a function that retrieves the target element from a dropdown menu:

function getTarget(evt){

 var targetElement = null;

 //if it is a standard browser
 if (typeof evt.target != 'undefined'){
  targetElement = evt.target;
 }
 //otherwise for IE, use different syntax 
 else{
  targetElement = evt.srcElement;
 }

 //return id of <li> element when hovering over <li> or <a>
 if (targetElement.nodeName.toLowerCase() == 'li'){
  return targetElement;
 }
 else if (targetElement.parentNode.nodeName.toLowerCase() == 'li'){

    return targetElement.parentNode;
 }
 else{
  return targetElement;
 }

This function works well in Firefox, Chrome, Safari, and Opera, but encounters issues in IE8 (likely in previous versions as well). When I try to debug it with IE8, I receive an error "Member not Found" on this line:

targetElement = evt.srcElement;

followed by other subsequent errors, indicating that this is a key line causing the problem. Any assistance would be greatly appreciated.


Apologies for the formatting issue encountered earlier.

Below is the function again:

function getTarget(evt){

var targetElement = null;

//check for standard browser target
if (typeof evt.target != 'undefined'){
    targetElement = evt.target;
}
//handle IE specific syntax and target retrieval
else{
    targetElement = evt.srcElement;
}

//return id of <li> element when hovering over <li> or <a>
if (targetElement.nodeName.toLowerCase() == 'li'){
    return targetElement;
}
else if (targetElement.parentNode.nodeName.toLowerCase() == 'li'){

            return targetElement.parentNode;
}
else{
    return targetElement;
}

// end getTarget

Answer №1

One issue lies with Internet Explorer, where the event object does not get passed as an argument to the handler function; instead, it is accessed through the global property (window.event):

function determineTarget(event){
 event = event || window.event; // retrieve window.event if argument is falsy (in IE)

 // obtain srcElement if target is falsy (IE)
 var targetNode = event.target || event.srcElement;

 //return id of <li> element when hovering over <li> or <a>
 if (targetNode.nodeName.toLowerCase() == 'li'){
  return targetNode;
 }
 else if (targetNode.parentNode.nodeName.toLowerCase() == 'li'){

    return targetNode.parentNode;
 }
 else{
    return targetNode;
 }

Answer №2

In my personal experience, the issue you are describing does not stem from where the event is sourced (window or handler parameter), but rather from how the event was triggered "correctly". For instance, if you have a text input field and invoke its onchange method without providing an event object, the event.srcElement property may end up being null.

To address this problem, consider using the code snippet shared by UniqueWebsite.

function triggerEvent(element, event){
   if (document.createEventObject){
      // for IE
      var evt = document.createEventObject();
      return element.fireEvent('on'+event,evt)
   }
   else{
      // for Firefox + other browsers
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent(event, true, true ); // event type, bubbling, cancelable
      return !element.dispatchEvent(evt);
   }
}

Here's an example of how to use this function:

triggerEvent(element,'change');

Answer №3

Smallest version of code:

function retrieveSelection(element) {
var event = element || window.event;
return event.srcElement || element.target;
}

Answer №4

I also encountered this issue. The problem arises when using IE8, where the event needs to be accessed as window.event instead of through the parameters.

To resolve this issue, I made the following adjustments:


    function handleClick(event){
      if (isIE8()){
        clickedElement = window.event.srcElement;
      } else {
        clickedElement = event.target;
      }
    }

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 process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

Organizing AngularJS ng-repeat into sets of n items

I am facing a challenge with a data set structured like this: $scope.items = [ { model:"A", price: 100, quantity: 30}, { model:"B", price: 90, quantity: 20 }, { model:"C", price: 80, quantity: 200 }, { model:"D", price: 70, quantity: 20 ...

Exploring the World with the vue-i18n Plugin

Recently, I have integrated translation into my app and now I am looking to implement a button event that allows users to change the language on the home page. For this task, I referred to two tutorials: Localization with Vue and Localization with Vue Tut ...

Struggling with TypeScript declaration files has been a challenge for me

I'm encountering an issue with using the trace function in my TypeScript code. The function has been declared in a .d.ts file as shown below: declare function trace(arg: string | number | boolean); declare function trace(arg: { id: number; name: strin ...

Difficulty arises when applying hover effects to animations using callbacks

Currently facing an issue with the hover event in jQuery. There are two side-by-side containers with hover events on both. When hovering, a div containing additional information slides up into view and slides back down when the hover ends. The concept is ...

Incorporating JavaScript into a pre-existing HTML and CSS user interface

After successfully coding a chat app UI for my project site using CSS and HTML, I am now facing the challenge of adding functionality to my existing code. The issue is setting up the client server and integrating chatting functions into my current UI. Mo ...

Do I need to manually destroy the directive scope, or will Angular take care of it

I have a question about directives in Angular. Let's say we have a directive called "myDirective". Here is the corresponding HTML: <div my-directive> </div> When we remove this <div> element from the DOM, will Angular automatically ...

Efficiently Loading AJAX URLs using jQuery in Firefox

setInterval(function(){ if(current_url == ''){ window.location.hash = '#!/home'; current_url = window.location.hash.href; } else if(current_url !== window.location){ change_page(window.location.hash.split('#!/&apo ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

Accepting insecure certificates in Chrome with Selenium-Webdriver in JavaScript: A Step-by-Step Guide

After generating a test script using Selenium-IDE in Javascript-Mocha format, I encountered an issue with an insecure certificate when trying to access a remote URL locally. To address the problem, I need to modify the generated TestScript to include Chro ...

When downloading files in Chrome or Safari, the $ajax call is in a pending state, whereas in IE or Firefox,

Measuring the time it takes to download a 1MB file using AJAX calls. Below is the code snippet: var start = new Date(); $(document).ready(function() { $.ajax ({ url: 'https://www.example.com/dummyFile1024', crossDomain: t ...

What is the best way to implement Redux within Next.js 13?

Currently, I am using Next JS 13 with Redux. In Next.js 12, I was able to wrap my entire application with Provider inside ./pages/_app. However, how can I achieve this in Next JS 13? Here is the code from my layout.js: import "../styles/globals.css&q ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

Is it possible for me to include a static HTML/Javascript/jQuery file in WordPress?

My extensive HTML file contains Javascript, jQuery, c3.js, style.css, and normalize.css. I am wondering if I can include this file as a static HTML page within Wordpress. Say, for instance, the file is called calculator.html, and I want it to be accessib ...

"Enhance your website with Ajax code that enables automatic refreshing of a PHP file, keeping its values up-to-date

Before diving in, I want to make it clear that my understanding of ajax is limited. I'm currently working on a small application where I have a load.php file that echoes 3 variables: $loadout[0]; $loadout[1]; $loadout[2]; The PHP file is functioning p ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...