4

I have this button that is loaded whenever u click another button(so its not loaded on startup without me doing anything)

<button type='button' id='testbtn' 
onclick='testfunction()' onload='testload()' 
class='testbtnclass'>btn</button>

This is my function:

 function testload() {

alert("onload worked");
 /*what i want to archieve within this function later is to change the
 css of the button but for now i just want to call this function onload of 
 the button, which it doesnt/*
}

My question is now, how can i/should i do to get this function to run whenever this button is loaded?

3
  • Jquery allowed or only javascript ? Commented Apr 30, 2015 at 8:39
  • So you have btnA, when you click on it it generates btnB, and then you want to fire an event when you created btnB? Commented Apr 30, 2015 at 8:39
  • why not do it on document.onload ? it wil be same Commented Apr 30, 2015 at 8:40

4 Answers 4

1

onload is not supported by button tag so you need to do it either as other answer telling or with

document.onload =function(){

  //change the css of that button or call function you want 

}
Sign up to request clarification or add additional context in comments.

Comments

1

I believe you can create a css class example:

.buttonStyle{ background-color: red };

Then you can get your button and add this class

var button = document.getElementById("testbtn");
button.className = button.className + " buttonStyle";

Comments

0

using jQuery you can do just the following:

$( "button" ).addClass( "myClass yourClass" );

Comments

0

You could use event delegation of jQuery. With this technique, it doesnt matter if the button gets generated after DOM is loaded.

$('body').on('click', '.generated_btn', function() {
    //here you can change css
});

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

More information: https://learn.jquery.com/events/event-delegation/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.