Loop through jQuery - javascript

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

Related

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's toggle function is affecting too many elements

This is what should happen: When I click an image '.post-text' should appear, then - when I click the image once more - the image disappears. All this happens in the toggle function but I have simplified it here.
This is what actually happens: When I click one image, the '.post-text' of all the blocks are opened immediately. I need that to only open the one that I click. I have tried what you see below and the find function, but it doesn't work. Please help me.
$( ".down-text img" ).click(function() {
$(".post-text" ).toggle( "slow" );
});
You can use classes
but with that you will be needing some traversing
supposing your .post-text is the next div after your image
$( ".down-text img" ).click(function() {
$(this).next(".post-text" ).toggle( "slow" );
});
see jquery next() | find() | parent()
https://api.jquery.com/next/
https://api.jquery.com/parent/
https://api.jquery.com/find/
You should use $(this) to target the element you just clicked:
$( ".down-text img" ).click(function() {
$(this).find(".post-text" ).toggle( "slow" );
});
Data attributes can help here.
If you add a data attribute called text to your HTML image element:
<img data-text="text1"/>
And a matching one to your text element:
<div class="post-text" data-text="text1">Here is some text</div>
You can then use that information to only open the correct text element rather than all of the elements that share the same class:
$('.down-text img').click(function () {
var id = $(this).data('text');
$('.post-text[data-text="' + id + '"]').toggle("slow");
});
DEMO

jQuery/JS/etc menu builder

I am trying to build an application. I want to allow users to create their own menu (with submenus also). I want to make this with JavaScript to be "live" (something like: to click add a button and then drag and drop to order etc).
Do you think is there any jQuery/JavaScript/etc menu builder already for download?
I have tried to search menu builder javascript/jquery but I only found online menu builders (not to download).
Any type of code is accepted (related to js) - jquery, js, mootools etc
Thanks a lot!!! If the question isn't asked in the right place I will delete.
Edit: I don't need custom styles like "select a design for menu". It only needs t generate HTML <ul> and <li>
Try using jQuery UI alongside with jQuery (you must put jQuery UI script after jQuery and you must include a CSS theme e.g UI lightness). Start off with a <ul> and give it an ID (e.g #menu). Put all the base <li>s inside of it with the default values and the drag-and-drop <ul>s in a different element, e.g #items. Then in your script file, put:
$(function() {
$( "#menu" ).menu();
});
This will turn the ul into a menu. Now you want to make the items drag-and-droppable. In the same function, add this underneath $( "menu" ).menu();:
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
This will let you sort the menu items. To let you move them from place to place, add this to your function underneath ...disableSelection();:
$( "li" ).draggable();
$( "#menu li" ).droppable({
drop: function( event, ui ) {
$( this )
.appendTo( "#items" );
}
});
$( "#items li" ).droppable({
drop: function( event, ui ) {
$( this )
.appendTo( "#menu" );
}
});

Update text, without clearing icons in table?

I have a table that you can select rows and edit fields with from a dialog. These table rows typically have an icon for drag and drop capability, as well as an icon for attachments. The issue is that when you edit the text from the dialog, the icons clear regardless of whether I use .html() or .text(). I believe using a form of .content() is viable, but I'm not sure how to go about it. I've tried to avoid clearing the images with .not() with no luck. Any ideas? Thanks in advance. http://jsfiddle.net/BWCBX/11/
$( ".saveBtn" ).click(function() {
properties.eq(0).html($("#name").val());
properties.eq(1).html($("#perm").val());
});
With what you have you can just replace the text like this:
$(".saveBtn").click(function () {
properties.get(0).firstChild.nextSibling.nodeValue = $("#name").val();
properties.eq(1).text($("#perm").val());
$(".prop").dialog("close");
});
Fiddle
But it would be better to wrap your text in another element, and set the value for it for better operation.
you can use .content() like this
$( ".saveBtn" ).click(function() {
properties.eq(0).contents()[1].textContent=$("#name").val();
properties.eq(1).html($("#perm").val());
$( ".prop" ).dialog( "close" );
});
http://jsfiddle.net/BWCBX/19/
Edit
if you need the code to work on IE lower than 9 you can do this
$( ".saveBtn" ).click(function() {
properties.eq(0).contents().eq(1).wrap("<span></span>").parent().html($("#name").val());
properties.eq(1).html($("#perm").val());
$( ".prop" ).dialog( "close" );
});
http://jsfiddle.net/BWCBX/20/

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

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.

Categories

Resources