JavaScript onClick does not work in Firefox

11,767

Solution 1

In Firefox, however, the trigger does not seem to work. Any ideas why?

Firefox does not make the event object global. You have to pass it along to the event handler, e.g.

onClick="openPopup('#popup1', event)"

Since you are using jQuery, you should bind the handler with jQuery so that you can also use jQuery's augmented event object.

Solution 2

I think what you might be experiencing is a problem with the uppercase C in onClick. Try changing it to onclick (all lowercase).

See this question: onclick or onClick?

Also you may have trouble accessing the event object: Access global event object in Firefox

But it the case of your example I don't think you will need it.

event.preventDefault prevents the browser trying to follow a href of a link when it is clicked (you don't have an href in your example). If the link gets followed, and your browser navigates to another page you will not get a chance to see any error that may have happened and it can be very frustrating to work out what is going on, so if you do need to use event.preventDefault make sure it is on the first line of the function it is in

Share:
11,767
Frank
Author by

Frank

Data Engineer (2 years) at major financial firm, financial algorithms freelancer, tutor at university and Big Data enthusiast.

Updated on November 28, 2022

Comments

  • Frank
    Frank 11 months

    I have a confirmation popup that opens when a user clicks on this link:

    <a onClick="openPopup('#popup1')">foo</a>
    

    here is the relevant JavaScript:

    function openPopup(id) {
    
       $(id).show();
       event.preventDefault();
       $(id).addClass('is-visible');
       $(id).css("z-index", "999999999999999999999999");
    
    }
    

    In Safari and Chrome it works fine. In Firefox, however, the trigger does not seem to work. Any ideas why?

    I already tried to change the link like so:

     <a href="javascript:openPopup('#popup1');">foo</a>
    

    no changes though. thanks for your help!

    • bpeterson76
      bpeterson76 over 8 years
      If you're using jQuery as the tags indicate, the better practice would be to catch the click event in a $('selector).on('click', function(){}) Inline javascript becomes a major maintenance nightmare.
  • Frank
    Frank over 8 years
    thanks for your answer! I am not really sure how to use the event handler, which element should go in there?
  • Felix Kling
    Felix Kling over 8 years
    I don't understand what you mean.
  • Frank
    Frank over 8 years
    well, you are adding "event" into the function call, the function would have to be adjusted too, right?
  • Felix Kling
    Felix Kling over 8 years
    Yes. function openPopup(id, event) {