eastwater
eastwater

Reputation: 5582

calling a function before onclick script

<a href="#" onclick="foo()">click me </a>

Hello, I need to called a function before calling the onclick script when the is clicked.

I tried:

    var script = $("a").attr("onclick");
    $("a").attr("onclick", "");

    $("a").click(function(event) {
       // call bar() first, then foo();
       bar();
       // script is a string on Chrome
       // foo() may use this, so can not globalEval.
    });

how to call the script? Can I get the onclick as jQuery function? so that:

 onclickFunction.call(this);

Thanks.

Upvotes: 1

Views: 10673

Answers (3)

alan9uo
alan9uo

Reputation: 1131

You can add "mouse up" or "mouse down" event to the element, this event will call before the "click" event call. Here is the demo.

void function(){
  $("div").mousedown(function(){
  console.log("mouse down event") 
  })
  $("div").mouseup(function(){
  console.log("mouse up event") 
  })
  $("div").click(function(){
  console.log("click event") 
  })
}();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>click me</div>

Upvotes: 1

psieniarski
psieniarski

Reputation: 111

If you must follow this way try this:

JS:

(function() {
    var a = document.getElementsByTagName('a')[0];
    var foo = a.onclick;

    function bar() { console.log('bar'); } 

    a.onclick = function() {
        bar(); 
        foo();
    };
})();

jsfiddle

Upvotes: 3

guilhebl
guilhebl

Reputation: 8990

can't you wrap them inside another function like this? :

<a href="#" onclick="handler();">click me </a>

var handler = function() {
   foo(); // 1. calling foo first
   bar(); // 2. calling bar second
};

Upvotes: 0

Related Questions