How to use a script with variables? JS

0

I want to create a custom JavaScript:

Ex:

var lx = function(addr){window.open(addr, '_self'); }

But it did not work.

I used up visual studio 2012 to edit this script but html did not recognize the function

lx('www.google.com');
    
asked by anonymous 08.07.2014 / 14:01

1 answer

2

HTML

<button id="open">Clique aqui</button>

JAVASCRIPT

function open (address) {
    window.open(address, '_blank');
};

var button = document.getElementById('open');

button.addEventListener('click', function () {
    open('http://google.com');
});

And do not forget to put http at the beginning of the link as it can be interpreted as a folder.

DEMO, Thanks @Guilherme Oderdenge

For your method to work, the code must run in the same file.

HTML + JAVASCRIPT

<html>
<head>
   /* CSS, SCRIPTS, ETC.... */
  <script type="text/javascript">
       var lx = function(addr){ window.open(addr, '_self'); }
  </script>
</head>
<body>
  <script type="text/javascript">
      lx("http://www.google.com");
  </script>
</body>
</html>

Another option is to use window.location if you want to open in the same window / tab

var lx = function(addr){ window.location = addr; }
    
08.07.2014 / 14:18