Reputation: 333
i am a newb at jquery so pardon the question: here is my html
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src=teacher_index.js></script>
</head>
<body>
<div id="lessons_viewer">
</div>
</body>
here is my js:
var data=[
{image:"reading_practice.png"},
{image:"drag_meaning.png"}
]
function populate_lessons_viewer(data){
for (var i=0,count=data.length;i<count;i++){
$('<img/>', {
className: 'lesson_image',
src: data[i].image
}).appendTo('#lessons_viewer');
};
};
$(document).ready(populate_lessons_viewer(data));
what am i doing wrong? the images are not appending!
ps i know how to do it in js but i am trying to learn jquery.
again i apologize for my newb mistakes and questions but... when i moved the:
$(document).ready(populate_lessons_viewer(data));
statement into the html doc... instead of the js doc it works. if someone could please explain i would greatly appreciate.
Upvotes: 0
Views: 67
Reputation: 942
Your problem is with the $(document).ready() statement. Since you have an argument in the function, it is evaluating the function and sending that to the ready() function. You want to send the whole function into it.
One way to accomplish this using $(document) would be to just pass the function name, since data is already a global variable.
function populate_lessons_viewer() {
//...
};
$(document).ready(populate_lessons_viewer);
Or, as preferred in most jQuery applications, you can use the init() function. If you have ever used a C language, this is similar to placing your code in the main() function. It will start after the document is loaded.
data = [
{image: "foo.png"},
{image: "bar.png"}
];
$(init);
function init() {
//your code, such as:
populate_lessons_viewer(data);
//...other initial functions
}
function populate_lessons_viewer(data) {
//....
}
UPDATE: Another option I just thought about is encapsulating that function in another function:
$(document).ready(function() {
populate_lessons_viewer(data)
});
I have tested this and it does work. You wouldn't have to change the rest of your code.
Upvotes: 1
Reputation: 33661
You already declared your data variable.. no need to pass try and pass it into your document.ready function
var data=[
{image:"reading_practice.png"},
{image:"drag_meaning.png"}
]
A normal document.ready function is like this
$(document).ready(function() {code here ...});
You are trying to do
$(document).ready(function(data){code here ...});
You just need to get rid of the data arguments since you already declared the variable
function populate_lessons_viewer(){
for (var i=0,count=data.length;i<count;i++){
$('<img/>', {
className: 'lesson_image',
src: data[i].image
}).appendTo('#lessons_viewer');
};
};
$(document).ready(populate_lessons_viewer);
Upvotes: 1