MShack
MShack

Reputation: 652

attr new onclick function not working

I am replacing an onclick attr as so....

$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}

My current html is

<div id="divName" onclick="oldFunction()">

and after i insert the new attr , inspecting element shows this

<div id="divName" onclick="newFunction()">

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

Upvotes: 2

Views: 2654

Answers (4)

Sibtain
Sibtain

Reputation: 108

I were facing the same issue. Checked on the console.It showed onclick="newFunc()" but when inspected the button it shows oldFunc() after click oldFunc() invoked. Simply replaced my code with pure JavaScript i.e used document.getElementbyId and used setAttribute() for updating onclick.

var btn=document.getElementById('myBtn');
btn.setAttribute('onclick',"test()");

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You should use unobtrusive event handler and use .on() to attach event handler

var $elem = $('#divName');

//Remove previous event handler
$elem.prop('onclick',null);

//Bind new event handler
$elem.on('click', newFunction);

function oldFunction() {
  console.log('old funnction.');

  var $elem = $('#divName');

  //Remove previous event handler
  $elem.prop('onclick', null);

  //Bind new event handler
  $elem.on('click', newFunction);

  console.log('New Event handler attached, click again');
}

function newFunction() {
  console.log('New Function Success');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divName" onclick="oldFunction()">click me</div>

Upvotes: 3

Haroon
Haroon

Reputation: 111

Since jQuery provides .click() function, you can user this instead. Please try the below solution. Remove the onlick and attach click() to div

$("#divName").attr("onclick","").click(newFunction);

function newFunction(){
    alert('New Function Success');
}

Upvotes: 0

Gilang Pratama
Gilang Pratama

Reputation: 431

I don't know what the purpose of that codes. but i try to give you another solution. Hope will solve your problem.

html:

 <div id="divName" onclick="oldFunction()">

on script:

 $('#divName').addClass('newClass');

 $('.newClass').click(
   function(){
    alert('New Function Success');
   }
 );

if you need to change another function you can change your attribute.

Upvotes: 0

Related Questions