How to create functions for extension

Asked

Viewed 402 times

1

I’m creating an extension, my first extension for Google Chrome, the extension consists of changing elements of any page and change things, but wanted to put a function to a button via onclick, but it doesn’t work! Suppose the site has the following structure HTML:

<button class="one" onclick="funcaoOriginal();">Teste</button>

In the archive js of the extension have the following:

function minhaFuncao(){
alert('teste');
}

$('.one').attr('onclick','minhaFuncao()');

but it doesn’t work! , if so:

$('.one').attr('onclick','alert(\'teste\')');

It works, but I want to put things like $.each and $.cookie inside a function and call it by clicking on the button of the site.

How would I do that?

  • 1

    Where’s that minhaFuncao() code? is in the global scope or within another function such as .ready()?

  • 2

    And why not use $('.one').on('click', minhaFuncao);?

  • Within the .ready() @Sergio, I tried to $('.one').click(function(){ //codigo }); and it worked! had not thought before. thank you very much.

1 answer

1


When you have function calls inline in HTML then these functions have to be in the global scope. If you put inside another function like the .ready() then they are only accessible within this function and no longer in the global scope.

You have two choices:

  • put in the overall scope and keep the call to function inline in HTML

HTML:

<button class="one" onclick="funcaoOriginal();">Teste</button>

Javascript:

function minhaFuncao(){
    // fazer algo
}
$(document).ready(function(){
    // resto do código...
  • use an event headset

In that case you can withdraw onclick="funcaoOriginal();" of HTML and use

 $('.one').on('click', function(){
     // código
 });

or using the function declared separately

$('.one').on('click', minhaFuncao);

This second alternative is better. Mix Javascript inline in HTML is not good solution. If you use $('.one').on('click', minhaFuncao); remember that this line and the function declaration must be in the same scope. They can both be within the .ready() or another block of code, but they must be in the same scope.

  • Thank you very much for the explanation Sergio.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.