0

I'm supposed to create a custom event triggered on page load that adds a class 'green' to the div with the id #myElementId. This is my attempt at the code but I'm getting an error message saying that I have to add the class green. Can you tell me what I'm doing wrong?

$(document).ready(function(){

 $('#myElementId').bind('ready', function() {
      $(this).addClass('green');
    });
});

HTML

<body>
<div id="myElementId"></div>

</body>

Update

This is taken from a codecademy lesson that's supposed to teach me how to create a custom event that adds a class on page load, so even though there are other simpler solutions, I'm trying to solve it the way the lesson intended.

this is the hint they gave

$("#myElementId").on("myCustomEvent", function(event) {
});
6
  • Pretty sure divs don't have onready events. Commented Sep 7, 2012 at 22:31
  • What is the exact error message you get? Commented Sep 7, 2012 at 22:32
  • It's through a codecademy exercise, custom error message. Oops, try again. You need to give the div the class '.green' Commented Sep 7, 2012 at 22:33
  • Why do you want to use an event instead of just $('#myElementID').addClass('green')? Commented Sep 7, 2012 at 22:34
  • @bfavaretto see update in the OP Commented Sep 7, 2012 at 22:35

2 Answers 2

3

You could just do:

$(document).ready(function() {
    $("#myElementId").addClass('green');
}​);​

Also note that you have typo in your id. It's myElementId, not myElementID.

EDIT: To trigger an event, use .trigger():

$(document).ready(function() {

 // Bind a function to be executed when 'myCustomEvent' is triggered
 $('#myElementId').bind('myCustomEvent', function() {
   $(this).addClass('green');
 });

 // Trigger the event 'myCustomEvent'
 $('#myElementId').trigger("myCustomEvent"); 

});​

Also, as of jQuery 1.7, you should use .on() instead of .bind().

DEMO.

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

1 Comment

thanks for pointing out the typo. However, the point of the exercise is to create a custom event that adds a class 'green' on page load.
0

Just add the class by name green in the CSS .. That should get the work done for you..

.green
{
    font-weight: bold;
    background-color: green;
}

Check this FIDDLE

Also you do not need this line

$('#myElementID').bind('ready', function() {

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.