0
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">

var mySite={};

mySite.title=$('h1');
mySite.makeRed= function(){
return mySite.title.css('color','red');
};


$(document).ready(function() {

mySite.makeRed();


});


</script>

Good day. Why does the method called inside the function doesn't return anything?

2
  • Can you explain your question? Commented Mar 26, 2012 at 6:24
  • What do you mean by return? You have a problem with the title selector. mySite.title=$('h1'); will not select the h1 element at this time, because the DOM is not ready. It must be inside a $(document).ready() handler to be able to select that element. Commented Mar 26, 2012 at 6:25

2 Answers 2

1

I suppose those script tags are in the HEAD of the document.

When you do this outside the ready handler:

 mySite.title=$('h1');

The element h1 does probably not exists yet in the DOM. This is the purpose of the ready handler: make sure the DOM is ready to work with.

You can either move your script tag at the end of the body (right before the </body> tag). This has the same result as the ready handler as the DOM is parsed sequentially.

Or you could grab you H1 element inside the ready handler.

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

2 Comments

Is there anyway I can initialize and then just call the method upon loading?
...Move your script tag at the end of the body (right before the </body> tag)...
0

You have misspelled some things.

var mySite={};

mySite.title=$('<h1/>').html("Hello World"); // Set some text and create the tag tag!

mySite.makeRed= function(){
return mySite.title.css('color','red');
};


$(document).ready(function() {



   $("body").append(mySite.makeRed()); // Append it to the dom

});​

http://jsfiddle.net/eZzYz/1/

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.