JQuery add click event to unknown div id - javascript

I'm loading a php page that shows multiple elements, depending of the users (so i can't know how many items will be show). Those elements looks like :
<div id='container_feed'>
<div id='feed_element' data-userid='4'>Random Dude</div>
<div id='feed_element' data-userid='5'>Random Dude 2</div>
</div>
I'd like to add a click() event on each div and load a page depending of their userid HTML5 tag with .load()
I tried child(), each(), and some other method whithout success...
How can i add this event ?
Thanks.

Why not just delegate all the clicks like so:
/* You could also use '>div' if you can't guarantee the class name */
$('#container_feed').on('click', '.feed-element' , function() {});
That way, you're only adding the one event initially, but all divs inside will be handled by the click event. No need to loop through each element, using .children or .each or even $('#container_feed .feed-element').
Delegation is your friend.

First, don't use multiple IDs of same name. Use a CSS-class.
Then access the userid in your click function like that:
Code Example:
$("div.feed_element").click(function(e) {
var clickedUserId = $(this).data('userid');
$('.userdata-container').load('ajax/userpage_' + clickedUserId +'.html');
});
Corresponding HTML:
<div id='container_feed'>
<div class='feed_element' data-userid='4'>Random Dude</div>
<div class='feed_element' data-userid='5'>Random Dude 2</div>
</div>
<div class='userdata-container'>
<!-- The Ajax Code is loaded into this container -->
</div>

you can't have the same id for different elements, that's the point for an id (it should be unique). Use a class instead or just all div children from the main div
$('#container_feed div').on('click',function(){
// do something, the the userid data, load the page somewhere, etc...
})
or use a class
html:
<div id='container_feed'>
<div class='feed_element' data-userid='4'>Random Dude</div>
<div class='feed_element' data-userid='5'>Random Dude 2</div>
</div>
js:
$('.feed_element').on('click',function(){
// do something, the the userid data, load the page somewhere, etc...
})
newer versions of jquery recomends "on('click',function(){})" instead of "click(function(){})", i guess "click" will be deprecated sometime in the future and "on" can also replace "live()"

Try like this..
$("div[id='feed_element']").click(function() {
// Your stuff
});
You should use class, As ID is always used for unique identification.

First i would not use the same feed_element id for all divs.
Try this
$('#container_feed').children().each(function(){
if($(this).attr('data-userid') == # you want){
$(this).click(function(){
//your stuff here
});
}
});

$(".feed_element").click(function(event) {
var userId = $(this).attr('data-userid');
//make your ajax call.
});

Related

How to test if this element is the first one with its class in the whole document?

I'm having troubles in coming up with a conditional to load a script.
I need a conditional that will recognize if this element is the first one in the whole document that has a certain class.
The thing is that I've done a BBCode for a phpBB forum, and I want to put all the scripts there instead of put some in the templates, but if I do that and if the BBCode is used multiple times in the same page, the scripts mess up.
For example, this is a structure:
<div>
<div>
<div class="some-other-stuff"></div>
</div>
</div>
<div>
<div>
<div class="youtube"></div>
</div>
</div>
<div>
<div>
<div class="youtube"></div>
</div>
</div>
I want it so the script loads for the first div with the "youtube" class. I haven't managed to try anything (yep, that clueless).
This is the script I want to use the conditional for:
<script>
$(document).ready(function() {
$(".youtubebbcode_button").click(function() {
$(this).siblings('.youtubevideo').stop(true, true).slideToggle("medium");
});
});
</script>
If the problem is that you are loading the same script block for each instance you could remove the click handler before adding it using off()
$(document).ready(function() {
$(".youtubebbcode_button").off('click').click(function() {
$(this).siblings('.youtubevideo').stop(true, true).slideToggle("medium");
});
});
then only the last instance would activate the click handler
You can test if a given element is the first one in the document with a given class like this:
if ($(".someClass").eq(0) === element) {
// element is the first one in the document with .someClass
}
Or, if you just want to apply an event handler only to the first element in the document with a given class name at a specific point in time, you can just use .first() or .eq(0) directly:
// apply click handler only to first element with a a class
$(".someClass").first().click(function(e) {
// click handler only for first element
});
Or, if you your situation is dynamic (e.g. items are being added to the page all the time and you only want the click handler to act if the element is currently the first one in the page), then you can use delegated event handling:
$(document.body).on("click", ".someClass", function(e) {
if ($(".someClass").eq(0) === this) {
// element clicked is the first one in the document with .someClass
}
});
You could use :eq jQuery Selector, for example:
$('.test:eq(0)').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Test 1</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>

jQuery and first element in the clicked element

i have 2 div elements, and if i click on the first div then should the other div which is inside of the clicked div displayed, but i can't understand who it works, my jquery code is so:
jQuery('.infobutton').click(function(){
var clickedID = jQuery(this).attr('id');
jQuery(clickedID).children('div').toggle();
});
<div class="infobutton" id="infobtn1">
<div class="content">some content</div>
</div>
I get everytime right id, i tried also with .first(), .parent(), .children('.content')
It's possible to do this with jQuery?
Let's presume you have HTML like this:
<div id="container" class="infobutton">
Some content
<div>Some other content</div>
</div>
Now let's walk through your Javascript:
jQuery('.infobutton').click(function(){
Find elements with the class infobutton and assign a click handler. This works fine.
var clickedID = jQuery(this).attr('id');
Put the id of that element in the variable clickedID. The value of clickedID is now container.
jQuery(clickedID).children('div').toggle();
Run the jQuery selector on clickedID. Here we have the problem. This can be boiled down to jQuery('container'). This looks for an element with the tag name container, not with the ID container.
In fact, the solution to all of this is not to use the ID at all. Instead, you can build the jQuery object with this, which is a reference to the clicked element:
jQuery('.infobutton').click(function(){
jQuery(this).children('div').toggle();
});
Inside the event handler this will refer the element to which the handler was attached to
jQuery('.infobutton').click(function(){
jQuery(this).children('.content').toggle();
});
Demo: Fiddle
Use this
jQuery('.infobutton').click(function(){
jQuery(this).children('.content').toggle();
});
this refers to the current element inside the event .
your code will work as
use jQuery('#'+clickedID) instead of jQuery(clickedID)

How to access a hidden Dom Element with jQuery?

I have a HTML Div (I'm using Twitter Bootstrap to hide-show div2) looking like this:
HTML:
<div id="div1">
<button id="mybtn">Button</button>
<div id="div2" class="modal hide fade span12" style="display: none;">
<button id="anotherButton" data-char="">AnotherButton</button>
</div>
</div>
With jQuery im trying to change the Value of data-char while im clicking on mybtn. But without success cause div2 is hidden. console.log($('#anotherButton')); return an empty array.
Is there a way to access hidden DOM with jQuery or Javascript?
*Edit: *
By trying this dont work better , return undefined:
$('#mybtn').live('click', function(e)
{
//or e.preventDefault();
$('#anotherbutton').attr("data-char", "assigned");
alert($('#anotherbutton').attr("data-char"));
});
You can assign it
Live demo
$(function(){
$('#anotherButton').attr('char', "assigned");
alert($('#anotherButton').attr('char'));
});​
on Button click
Live Demo
$(function(){
$('#anotherButton').attr('data-char', "assigned");
alert($('#anotherButton').attr('data-char'));
});​
It looks like data method will not work on elements which are in hidden state. You should use attr method.
This should work fine
$(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$("#anotherButton").attr("data-char","new value");
});
});
Working sample http://jsfiddle.net/kshyju/a7Cua/4/
The fact that it is hidden changes nothing. The problem is probably that the js code is before the button HTML. Either put it after, or put it in a listener like $(document).ready() to make sure it has been processed when your try to access it.
Try $(button:hidden)
This usually works for things like this,
Source:http://api.jquery.com/hidden-selector/

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

jquery toggling a div - how to do this with multiple ids?

I am new to Jquery. My setup is as follows:
I have a series of divs that need to be able to be toggled (display hidden and shown). Each div has an action that can be performed so a unique ID will be necessary to know from which div the event came from.
To toggle the div I have a button for each div (which is not located within the div to be toggled).
Right now without jquery, I use the button's onclick event to pass the ID of the corresponding div to be toggled. Using the unique ID I can do the following:
function toggleFlag(divId) {
var div = document.getElementById(divId);
div.style.display = (div.style.display=="block" ? "none" : "block");
}
divId is unique so I also know where the event comes from if action within the div is performed.
the anchor code looks something like this:
onclick="toggleFlag('id-111');"
where the '111' is the unique id
First off, is it even worth it to use jquery for this if the extent of my javascsript isn't much more complicated (aside from maybe simple ajax).
More importantly, how would this properly be done using jquery?
Update: I am very close to solving this. I managed to get it to work using one of the suggestions below requiring unique class names for each button. A couple of the methods suggest implementations where the class name is the same for all buttons (I want this in order to be able to statically assign styles to the button class), but I could not get these to work. Could somebody please elaborate on the solution? Thanks!
Let's say that you build your anchors to have an id that corresponds with the id of the DIV to toggle and further that they all have a common CSS class. For example,
Toggle
<div id="d_111">Some stuff.</div>
Now you could use jQuery to build the click handlers for all of these pretty easily.
$(function() {
$('a.toggleButton').click( function() {
var divId = $(this).attr('id').replace(/a_/,'d_');
$(divId).toggle();
});
});
You could do something like this:
HTML:
<button id="btnId1" class="divId1" value="Click me to toggle divId1"/>
<button id="btnId2" class="divId2" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("class");
$("#" + divId).toggle();
});
});
This approach has the advantage of only defining the event once for all buttons. You could also use another strategy for storing the div id in the button information, like a non-standard attribute - which jquery can pick up as well, or make the div id a part of the button id like so:
<button id="btn_divId1" value="Click me to toggle divId1"/>
<div id="divId1">div 1</div>
and then extract the id of the div from the id of the button clicked (personally this is the approach I'd take)
Hope this helps
EDIT: To answer the first question, yes you would benefit from doing this with jQuery since it would shorten the amount of code that you are writing and it would allow you to move to unobtrusively assigning events to the buttons which is a good thing :)
EDIT 2: Using non-standard attributes:
HTML:
<button id="btnId1" divid="divId1" class="btnToggle" value="Click me to toggle divId1"/>
<button id="btnId2" divid="divId2" class="btnToggle" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("divid");
$("#" + divId).toggle();
});
});

Categories

Resources