0

Ive created links that open in a new window (not tab) with inline javascript:

onclick="window.open(this.href, 'newwindow', 'width=370, height=280'); return false;"

Now I want to move this javascript to a reusable class. Why is the following not working?

  $(document).ready(function() {

    $('.open-new-window').click(function(){
      return false;
      window.open(this.href, 'newwindow', 'width=500, height=150'); 
    });


  });
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 4
    Because you are terminating your function with `return false` before any other actions occurred. – nicael Nov 03 '14 at 10:53

3 Answers3

0

function is return before window.open() function so return false; should be at bottom

 $(document).ready(function() {

    $('.open-new-window').click(function(){

      window.open(this.href, 'newwindow', 'width=500, height=150'); 
     return false;
    });


  });
Girish
  • 11,907
  • 3
  • 34
  • 51
0

Your function returns before executing window's open method.

Ben Griffiths
  • 1,676
  • 15
  • 13
0

When you copy the code from the inline on click handler the order is really important. a return stops the function and returns a piece of information. Once returned nothing after it runs. The correct code is:

$(document).ready(function() {
   $('.open-new-window').click(function(){
     window.open(this.href, 'newwindow', 'width=500, height=150'); 
     return false;
   });
});

If you wanted to prevent the click first you could do this instead:

$(document).ready(function() {
   $('.open-new-window').click(function(e){
     e.preventDefault();
     window.open(this.href, 'newwindow', 'width=500, height=150');
   });
});

The first method may get a deprecated error (event.returnValue is deprecated. Please use the standard event.preventDefault() instead)

Community
  • 1
  • 1
georgephillips
  • 3,540
  • 4
  • 23
  • 30