Home > OS >  I'm trying to add an OnClick function to an element after page load and then make that OnClick
I'm trying to add an OnClick function to an element after page load and then make that OnClick

Time:09-21

I'm trying to add an OnClick function to 4 elements element on page load and then make those OnClick functions change the text of a separate element. I tried creating a function called AddClick that specified the elementID and then sets an OnClick attribute and seperate function. (I did this four times for each element I want to have the new function activated on click.

I then asked the AddClick to run on page load.

Then I created the functions that would replace the old text of the seperate element. (These should be set to run when the elements are clicked.

Sorry in advance if this was the wrong approach/If I'm not clear. First time posting on here, any help appreciated.

For the HTML the text I am trying to alter is within a div with an ID, but the h4 does not have a specific ID and I cannot add one.

Here is the JavaScript I tried to implement:

<script type="text/javascript">
function AddClick(){
    //Name & Number
    document.getElementById("o_5794738").setAttribute('onclick', "NewText()");
    //Number
    document.getElementById("o_5794733").setAttribute('onclick', "OldText()");
    //Name
    document.getElementById("o_5794723").setAttribute('onclick', "OldText()");
    //None
    document.getElementById("o_5794728").setAttribute('onclick', "OldText()");
};

window.onload = AddClick;

function NewText() {
    document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>New Text</h4>"; 
}
function OldText() {
    document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>Old Text</h4>";
}

Any help is much appreciated.

CodePudding user response:

You can try this:

document.getElementById("demo").onclick = function() {myFunction()};

I found this example on https://www.w3schools.com/jsref/event_onclick.asp

CodePudding user response:

No need to add click event using load you can directly add the click event using .addEventListener (by the way .setAttribute is not for adding any event)

Simply use .addEventListener like this :
document.getElementById("o_5794738").addEventListener('click', NewText);

Read this for more info about .addEventListener()

Here is the demo snippet below :

document.getElementById("o_5794738").addEventListener('click', NewText);

function NewText() {
  document.getElementById("pt_fc_775338").getElementsByTagName("h4")[0].innerHTML = "New Text";
}
<button id="o_5794738">Click Me!</button>
<div id="pt_fc_775338">
  <h4></h4>
</div>

  • Related