Jump to content

Overwrite function call of onClick="..."


Recommended Posts

Hey guys!


I have another pretty simple problem.


I have some html-code with an onClick function call.

<table>	<th onclick="$(document).ready(somefunction());">		some stuff	</th></table>

Now I want to write a JavaScript function, to swap "somefunction()" with "someotherfunction()". How can I achieve that?


The purpose of all of this is, to create a <table><th> that does something on the first click, and something else on the second click.

Link to comment
Share on other sites

Don't use the HTML event attributes. they're only there for backwards compatibility for old pages.


The table needs a <tr> element around the <th> element.


First you need a way to access the element, for example an ID:

<th id="button">

Then you can access the element. I'll use jQuery syntax because that's what you're currently using:

$("#button").on("click", somefunction); // Parentheses () should not be used on the function name here

Inside somefunction you can remove the other event listener and add a new one:

function somefunction() {    // Do something    // ...    // Remove listener and add a new one    $("#buton").off("click", somefunction);    $("#buton").on("click", someotherfunction);}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...