Why do we wrap a bunch of statements inside $(function() {...............}); in jquery - javascript

So I see this code in jquery-ui docs and I wonder why all the statements are wrapped in $(function() {...});
The jquery docs says that $() enhance the object in it, but I fail to see why we need it here. Is it a convention or is it actually meaningful?
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
</script>

$(function() {}); is, for all intents and purposes, the same as $(document).ready(function() {});; although I believe it is called slightly before document ready.
What it does is call the code within the function when the document has finished being created. That is all the DOM tree will have been created by the time that function loads. This allows you to manipulate the DOM safe in the knowledge those objects will have been created at that time.
Here is an example:
<script>
//This code is called straight away, your DOM hierarchy may not
//be complete and the object #draggable may not have been created yet,
//as such draggable() may not work properly.
$( "#draggable" ).draggable();
//This code is called once the DOM tree is complete,
//as such you know all your objects have been created
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
</script>
See the jQuery documentation for a more thorough explanation

This is a shorthand for $(document).ready(function() {})
It executes once the whole document is loaded, rather than executing when it's encountered during the parsing.

It also creates a context for the items with-in its' statement block, and this just as important as
$(document).ready(function() {}), document ready.

Related

Loop through jQuery

I'm working on a component that displays information from an array on click of an image.
Without going into a lot of detail, for each of the 12 images I have displaying, they have certain ids that are relevant to that slot in the HTML. So #person_0 is associated with #bio_0, #close_0, etc. And #person_1 is associated with #bio_1, #close_1, etc.
What I am having trouble with right now is finding an efficient way to loop through jQuery similar to the below:
$( "#close_0" ).click(function() {
$( "#bio_0" ).hide();
});
$( "#close_1" ).click(function() {
$( "#bio_1" ).hide();
});
$( "#close_2" ).click(function() {
$( "#bio_2" ).hide();
});
Rather than write this 12 times, is there a simple means to loop through this? What I'm clear on is how to pass in a variable into the div id (i.e. #close_0 - where 0 would be the variable).
Any tips?
Ideally, if these elements have a class, then you would do $( ".someclass" ).click(...
If not, you can loop by ids like this:
for(var i=0; i<12; i++)
{
$( "#close_"+i ).click(function() {
$( "#bio_"+i ).hide();
$( "[id^=person_]" ).removeClass("active");
});
}
PS. I did not understand what you are trying to do with removeClass and if that's related to the elements you attach click events to

jQuery, Target HTML generated dynamically

I'm trying to add/remove classes with jQuery to HTML elements generated by JavaScript dynamically. More specifically, to prettyPhoto's HTML in a WordPress theme. I need to add/remove a class to prettyPhoto's main parent div based on the class of a deep child link. This class gets changed by prettyPhoto. And all this HTML appears only when you click on an image on the page. I don't want to fiddle with the actual prettyPhoto script (included in the theme core files), so trying to do it with a jQuery function.
The HTML generated is (roughly) like this:
<div pp_pic_holder>
<1st level child>
...
<6th level child>
<a pp_expand>
And my current js is like this:
<script>
jQuery( 'body' ).on('change', 'div.pp_pic_holder', function() {
jQuery( "a.pp_expand" ).parents( "div.pp_pic_holder" ).addClass( "contracted" ).removeClass( "expanded" );
jQuery( "a.pp_contract" ).parents( "div.pp_pic_holder" ).addClass( "expanded" ).removeClass( "contracted" );
});
</script>
This doesn't work. I've tried with different options with .on and .live following examples from about 15 similar questions here on Stack Overflow, but nothing... I almost don't know js, so reading through the event delegation documentation only broke my brain.
Please help.
Thank you!
UPD:
Thanks to #Pete for his suggestions.
The code that finally made this work is this:
<script>
jQuery( 'body' ).on( 'DOMSubtreeModified', function() {
jQuery( "a.pp_expand" ).closest( "div.pp_pic_holder" ).addClass( "contracted" ).removeClass( "expanded" );
jQuery( "a.pp_contract" ).closest( "div.pp_pic_holder" ).addClass( "expanded" ).removeClass( "contracted" );
});
</script>

jQuery Statment not working in separate file?

somehow my simple jQuery Statement is not working when I include it in my "head"-element topic like :
<script src="js/test.js" type="text/javascript"></script>
but when I use it in my "body"-element it just works fine like
<script>
$( "#testid" ).click(function() {
alert( "Handler for .click() called." );
});
</script>
I checked already with firebug that my test.js file gets included on my site correctly. So what do I wrong ? The test.js file looks exactly like the "script" part above just without the script-tags.
Any idea is appreciated :)
You're forgetting to tell jQuery to wait until the DOM ready before firing up your code:
$(function() {
$( "#testid" ).click(function() {
alert( "Handler for .click() called." );
});
});
When you include your code in the body tag after the target element your code will work. However, if you include it in the body section before the target element or in the head section your code would not work. It is therefore recommended to always wrap your code in DOM ready. DOM ready can be written in different ways:
All three of the following syntaxes are equivalent:
$( document ).ready( handler )
$().ready( handler ) (this is not recommended)
$( handler )
Check out the documentation: http://api.jquery.com/ready/,
and the tutorial: http://learn.jquery.com/using-jquery-core/document-ready/
Feels like I rip of Rajaprabhu but:
<script>
$(document).ready(function (){
$( "#testid" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
Try this..
<script>
$(document).ready(function(){
$( "#testid" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
Also make sure your script has been added after jquery scipt.

JQuery UI: is it possible to know where an object has been dropped?

what I want to do is to know where (not in terms of position (x, y), but a reference to the DOM element) an object was dropped.
I have a grid made up with divs where you can drop various items and I need to know which div on the grid was the item dropped on (getting its id would be fine). The callback function
function(event, ui) { //code here }
has just that ui object who doesn't apparently contain any information about this, but only about the draggable item or its helper.
What you need to use is the jQuery Droppable class, which you can read about in the jQuery docs.
Basically, for every element that you wish to be able to drop a draggable element on, you create a Droppable object, which will trigger once another object is dragged onto it. This is the example from the jQuery docs:
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
The $(this) in that example is the element you are looking for.

drop a draggable using jquery

Is there any way of dropping a draggable into the droppable by hardcoding and not by actually going into the browser and doing drag-drop??
Thanks in advance.:D
I don't know if I have understood very clearly, in any case I think it is curious perspective,if you mean to animate and do the same things if we have dragged a layer into a droppable layer.
I suppose you could do it like this:
http://www.jsfiddle.net/dactivo/QLTUS/
You use animate() to move the layer to the droppable, and then in the complete function, you imitate what normally happens in a dropping action, that is to say change the class, and there you can include whatever.
I mean it is not important the drop event, but what you execute in the drop event, that can be included in your complete event of the animation. I have encapsulated this in a function called layerDrop().
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
layerDrop();
}
});
$("#btnMove").click(function()
{
$("#draggable").animate({"left": $( "#droppable" ).offset().left ,"top": $( "#droppable" ).offset().top},
{
duration: 1000, specialEasing: { width: 'linear' },
complete:function()
{
$("#message").html("Completed!");
layerDrop();
//whatever
}
}
);
});
function layerDrop(){
$( "#droppable")
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
I think you mean to position a dragged option programmatically. If that is the case then look in the official jQuery draggable documentation: http://docs.jquery.com/UI/API/1.8/Draggable
It seems the short answer is:
To manipulate the position of a draggable during drag, you can either use a wrapper as the draggable helper and position the wrapped element with absolute positioning, or you can correct internal values like so:
$(this).data('draggable').offset.click.top -= x

Categories

Resources