Skip to content Skip to sidebar Skip to footer

Click Event In Chrome Vs Firefox Gives Different Targets?

TL;DR: Clicking this button gives different targets on the click event if you are in Firefox vs Chrome. Seems like there should be an elegant solution to this problem instead of ha

Solution 1:

Use this to refer to clicked element and if you're using a button, then make sure to really add the event on button and some element within it.

const guid = '05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9';
//Get the div with this GUID.const elem = document.getElementById(guid);
const button = elem.querySelector("button.delete-device");
//Add listener to delete the div when clicked.
button.addEventListener("click", delete_devices, false);
    
functiondelete_devices(e){
    let id = this.getAttribute('data-id');
    console.log("Deleting widget: ", id)
    const elem = document.getElementById(id);
    elem.remove();
    returntrue;
}
<divid="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9">Device widget
<buttondata-id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9"type="button"class="btn-floating btn-small waves-effect waves-light red delete-device "><iclass="material-icons">delete</i></button></div>

Notice that I removed event.preventDefault. I suppose you used it because you wanted to prevent form from being submitted. Any <button> is submit by default, to turn it to normal button do this:

<button type="button">This does not submit form</button>

Solution 2:

You don't need to reference e.target. In a DOM event handler, this refers to the element that triggered the event. If you set up the event handler on the button (the parent element), then the child element cannot be the trigger for the event.

Also, your code attempts to get the id of an element, but none of your elements has an id established for it. You've used data-id, which can be accessed via the element.dataset.attributeName syntax if needed.

//Get the div with this GUID.const guid = '05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9';
const b = document.querySelector("[data-id='" + guid + "']");

// Add listener to delete the button when clicked.
b.addEventListener("click", delete_devices);

functiondelete_devices(e){
    this.remove();
}
<buttondata-id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9"class="btn-floating btn-small waves-effect waves-light red delete-device "><iclass="material-icons"id="05c4d5b0-44c6-4e4f-a4dd-b5ac9029b3a9">delete</i></button>

Post a Comment for "Click Event In Chrome Vs Firefox Gives Different Targets?"