JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout.

Below is the code snippet causing the problem:

<html>
  <head>
    <style type="text/css">
      #layer1 {
        width: 370px;
        height: 220px;
        background-color: yellow;
      }
      #layer2 {
        position: relative;
        width: 130px;
        height: 47px;
        top: 10px;
        left: 10px;
        background-color: #CC0066;
      }
      #layer3 {
        position: relative;
        width: 200px;
        height: 100px;
        top: 10px;
        left: 150px;
        background-color: #334466;
      }

      #button1 {
        position: relative;
        top: 4px;
        left: 4px;
      }

      #button2 {
        position: relative;
        top: 4px;
        left: 4px;
      }
    </style>
  <body>
   <div id="layer1">
    <div id = "layer2">
      <input type="submit" id = "button1" value="Button 1 (onclick)"></input>
    </div>
    <div id = "layer3">
      <input type="submit" id = "button2" value="Button 2 (onmouseout)"></input>
    </div>
   </div>
   <script type="text/javascript">
    document.getElementsByTagName("body")[0].addEventListener("click", function() {print(event);}, false);
    document.getElementsByTagName("div")[0].addEventListener("click", function() {print(event);}, false);
    document.getElementsByTagName("div")[1].addEventListener("click", function() {print(event);}, false);
    document.getElementsByTagName("input")[0].addEventListener("click", function() {print(event);}, false);

    document.getElementsByTagName("div")[2].addEventListener("mouseout", function() {print(event);}, false);
    document.getElementsByTagName("input")[1].addEventListener("mouseout", function() {print(event);}, false);
    function print(elem) {
        alert("JavaScript alert\n\n" +
            "Element\n" + 
            "   Type: " + elem.relatedTarget.tagName + 
            "\n   Id: " + elem.relatedTarget.id +
            "\nEvent's name: " + elem.type +
            "\nMouse's coordinates" + 
            "\n   Screen: " + elem.screenX + ", " + elem.screenY +
            "\n   Window: " + elem.clientX + ", " + elem.clientY +
            "\n   HTML item: " + elem.offsetX + ", " + elem.offsetY);
    }
   </script>
  </body>
</html>

Error occurs on clicking the item: https://i.stack.imgur.com/KJ5We.png

However, it functions correctly with mouseout events: https://i.stack.imgur.com/kuwrH.png

I am puzzled by what could be wrong since I'm using the same function, only changing the event type.

Thank you in advance.

Answer №1

I made the necessary adjustments to these two lines in order to achieve the desired outcome:

"   Element Type: " + elem.target.nodeName +
"\n   Element Id: " + elem.target.getAttribute("id") +

Hopefully, this solution resolves any issues you were facing.

document.getElementsByTagName("body")[0].addEventListener("click", function() {
  print(event);
}, false);
document.getElementsByTagName("div")[0].addEventListener("click", function() {
  print(event);
}, false);
document.getElementsByTagName("div")[1].addEventListener("click", function() {
  print(event);
}, false);
document.getElementsByTagName("input")[0].addEventListener("click", function() {
  print(event);
}, false);

document.getElementsByTagName("div")[2].addEventListener("mouseout", function() {
  print(event);
}, false);
document.getElementsByTagName("input")[1].addEventListener("mouseout", function() {
  print(event);
}, false);

function print(elem) {
  alert("JavaScript alert\n\n" +
    "Element\n" +
    "   Element Type: " + elem.target.nodeName +
    "\n   Element Id: " + elem.target.getAttribute("id") +
    "\nEvent's name: " + elem.type +
    "\nMouse's coordinates" +
    "\n   Screen: " + elem.screenX + ", " + elem.screenY +
    "\n   Window: " + elem.clientX + ", " + elem.clientY +
    "\n   HTML item: " + elem.offsetX + ", " + elem.offsetY);
}
#layer1 {
  width: 370px;
  height: 220px;
  background-color: yellow;
}

#layer2 {
  position: relative;
  width: 130px;
  height: 47px;
  top: 10px;
  left: 10px;
  background-color: #CC0066;
}

#layer3 {
  position: relative;
  width: 200px;
  height: 100px;
  top: 10px;
  left: 150px;
  background-color: #334466;
}

#button1 {
  position: relative;
  top: 4px;
  left: 4px;
}

#button2 {
  position: relative;
  top: 4px;
  left: 4px;
}
<html>

<head>

  <body>
    <div id="layer1">
      <div id="layer2">
        <input type="submit" id="button1" value="Button 1 (onclick)"></input>
      </div>
      <div id="layer3">
        <input type="submit" id="button2" value="Button 2 (onmouseout)"></input>
      </div>
    </div>
  </body>

</html>

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

Pass the AngularJS object to a different MVC Controller when a button is clicked in the MVC view

When a button is clicked on the view, I need to pass an AngularJs object to another controller. CHTML <div ng-repeat="hotel in respData.hotels"> <button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability</bu ...

Choosing a specific element within another element of the same type using JQuery

I've created a complex nested HTML structure shown below: <ul class="root"> <li>Foo 1 <label class="bar-class">bar</label> <ul> <li>Foo 2 <label class="bar-class">bar</label> ...

The elements within the Popup Modal are not displaying as expected

I found a helpful tutorial that teaches how to display a Popup Modal Window when the page loads. However, I'm facing an issue where the modal is not showing the contents and images properly. The code I am working on can be found at jsFiddle. My goal ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Checking the validity of date inputs - microservice for timestamps

I'm encountering an issue while attempting to validate my date input. I've tried using moment js, but it seems there's a problem. The error message "date invalid" keeps popping up! Here is the code snippet: app.get("/api/timestamp/:date_s ...

Using AJAX to Transfer Numerical Data

I am new to javascript and I am trying to implement a LIKE button on my website. <a href="" onClick="likePost(<?php echo $post->ID; ?>); return false;">LIKE</a> Additionally, here is the function that I am using: function likePost( ...

Exploring discrepancies in JSON arrays using Lodash

Using lodash to find the difference between two arrays: c1Arr contains: [ { varName: 'city', varValue: 'cccccccc' }, { varName: 'country', varValue: 'dddddddd' } ] c2Arr contains: [ { varName: 'abc', ...

Press a button to link a click event handler to another button

function example() {console.log('example');} $('#button1').click(function(){ $('#button2').onclick = example(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...

Tips for updating or deleting a ref value within the VueJS 3 composition api

I am utilizing a ref value in order to only trigger a click event when the ref value is changing. For instance, if I need to update/delete the array inside let myRef = ref([]);, should I simply access the proxy and carry out the operations like this : sel ...

Bring in a pair of documents

Just started learning about imports and encountered a particular issue. After installing the package in your gulpfile, you must include the following line: const sass = require('gulp-sass')(require('sass')); Is there a way to achieve ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...

Dynamic Select Box with Display of 2 Buttons

Looking to create an Ajax combo box with options for Female and Male. I would like to display a button for Female and a button for Male. Here is the code that I have: <!DOCTYPE html> <html> <head> <style> #for-male, #for-female{ ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Leveraging jQuery to automatically fill in a time field while excluding other buttons

I've been working on using jQuery to automatically fill in a time input field. The functionality is working properly, but the time is also being applied to my other button. How can I make sure it only gets assigned to the time input field? I would re ...

It's next to impossible to secure expedited work on an ongoing project using Vercel

Yesterday, I successfully deployed an application on Vercel using only ReactJS. Today, I made the decision to develop an API for my application, To clarify, I have a folder housing the React app, and within that, I created a directory named "api" followi ...