Using jQuery 'this' with a selector of multiple elements - javascript

Sorry jQuery noob question here, I am attempting to make all of the div elements with the class .thumbnail clickable with a callback function. But, once one of the div(s) of that class is clicked I need the specific ID of that given div so I can do further manipulation to that specific one. I am confused if I would use 'this' to reference that specific div once it is clicked or if I am looking at this the wrong way.
Im sure this is a very simple question for you jQuery gurus to answer, its been a long day and my brain is completely zombified.
Example Sudo Code:
<script>
$(document).ready(function() {
$(".thumbnail").click(function() {
//need to get id of thumbnail that was clicked, this is where I am confused
var thumbnail_id = $(this).attr('id')
alert(thumbnail_id);
});
});
</script>
<div class=thumbnail" id="1">Tom</div>
<div class=thumbnail" id="2">Jerry</div>
<div class=thumbnail" id="3">Sue</div>
<div class=thumbnail" id="4">Mary</div>
<div class=thumbnail" id="5">Brian</div>

DOnt you think thumbnail should be written like "thumbnail" and not thumbnail"

It is unclear what your jQuery problem is. To address the question you're asking, when an object is clicked in your code, the click handler will be called and this will be set to the DOM element that was clicked on. This works if there is one object with the thumbnail class or many.
If your problem is really that your HTML is in error, then you should add the missing quote to change this:
<div class=thumbnail" ...
to this:
<div class="thumbnail" ...
FYI, a better way to do this is as follows. This fixes the quote problem and uses a data attribute rather than a numeric id value:
Working demo: http://jsfiddle.net/jfriend00/8tczB/
<script>
$(document).ready(function() {
$(".thumbnail").click(function() {
//need to get id of thumbnail that was clicked, this is where I am confused
var thumbnail_id = $(this).data('id');
alert(thumbnail_id);
});
});
</script>
<div class="thumbnail" data-id="1">Tom</div>
<div class="thumbnail" data-id="2">Jerry</div>
<div class="thumbnail" data-id="3">Sue</div>
<div class="thumbnail" data-id="4">Mary</div>
<div class="thumbnail" data-id="5">Brian</div>

Related

Write click event dynamically on jquery

Here is the original html
<div class='cl_{{ $gen }}'>{{$gen->name}}</div>
<div class='jl_{{ $var }}'>{{$gen->name}}</div>
After looping over here is the html i got as output
I wanted to do if i click on the class cl_x, then the jl_x should be visible and other should be hidden and by default the first cl_1 should be visible. How can i do this ?
<div class='cl_1'>One</div>
<div class='cl_5'>Two</div>
<div class='cl_6'>Three</div>
<br>
<div class='jl_1'>Alpha</div>
<div class='jl_1'>Andrew</div>
<div class='jl_1'>Christ</div>
<div class='jl_5'>Anto</div>
<div class='jl_5'>Brito</div>
<div class='jl_6'>Oyster</div>
<div class='jl_6'>Beta</div>
Note : All the 1,5,6 are not standard as they are coming from database.
I really can't able to think how to achieve this. Help pls
But Here is what i have tried the logic
Inside Document Ready
Loop over the jquery like html
Write click event to show hide if they cick on cl_*
Trigger the click event for first occurance.
Don't worry about the html generated but the need is to write the jquery events dynamically or something else
But can't able to implement the code pls help
Script :
$(document).ready(function() {
//not sure whether i should loop over the jquery itself or write anything like the element starts with cl-* like that
});
Update :
Here is the Fiddle i have so far
You don't really want to use class for this - a custom data attribute makes sense, though. Like <div class="cl" data-number="{{ $gen }}"> with <div class="jl" data-number="{{$var}}"> on the other elements.
Then inside the $(document).ready(...) you can do something like:
$('.jl').hide().first().show();
$('.cl').click(function(){
$('.jl').hide().filter('[data-number="' + $(this).data('number') + '"]').show();
})
It would also be good to make up more meaningful names than "cl" and "jl" - classes should generally be semantic.
Would move the unique identifiers to a different attribute and add a common class to all the J group
<div class='cl' data-gen="{{ $gen }}">{{$gen->name}}</div>
<div class='jl jl_{{ $var }}'>{{$gen->name}}</div>
JS
$(document).on('click','.cl',function(){
$('.jl').hide().filter('.jl_' + $(this).data('gen') ).show();
})
Add a base "jl" class to all your html that has anything with a "jl_*" so that you will have access to anything overall that has the "jl" class then toggle it hidden or not hidden like so:
HTML:
<div class='cl {{ $gen }}'>{{$gen->name}}</div>
<div class='jl {{ $var }}'>{{$gen->name}}</div>
JS:
$(document).on('click', '.cl', function(e){
var classes = ($(e.target).attr("class").split(' '));
$('.jl').toggleClass("hide");
$('.jl' + "."+ classes[1]).toggleClass("hide");
});
Style:
.hide{
display: none;
}
https://jsfiddle.net/rc368gjp/

Id=' ' within id=' ' with javascript and onmouseover="this.click();" function

I am a beginner in Javascript and I am not absolutely sure how to put together the function what I try to achieve.
So, I have a HTML5 page and I must stick to my ID structure as different functions are tied to IDs.
My problem is I have an id within an id (It must stay an ID, it cannot be swapped with class)
E.G.
<div id="outterid">
CLICK ME
<div id="innerid">
<p>Hello World</p>
</div>
</div
Where, <div id=outterid"> pops up as a tooltip (My other javascript takes care of that function. And within that the link CLICK ME and the hidden <div id=innerid">.
So when you click CLICK ME, <div id=innerid">becomes visible. (Note: <div id="outterid"> is visible, while you are clicking)
So I need to achieve the href="#innerid" through javascript, because at the moment simply href=""
E.G.
CLICK ME
does not work, because the #innerid within the #outterid.
Also, the 'CLICK ME' link has to be triggered by onmouseover="this.click();". So, the link clicked when the mouse hovers over it.
I hope I managed to clearly explain what is my problem and what result I am looking for.
Thanks for your help in advance.
Are you talking here about scrolling to the relevant div (e.g. #innerid)? In which case I don't think your problem has anything to do with javascript, but rather you've missed the a off of <href="#innerid">CLICK ME</a>... I've tried replicating your problem in JSFiddle and with CLICK ME it scrolls to the correct div regardless of if it's in a nested outer div or not.
It's not clear exactly what you're after here but i've had a shot. This example will display the #innerid div when you click on the anchor tag. Hopefully this will help you.
function myFunction(href) {
var id = href.split('#')[1];
document.getElementById(id).style.display = 'block';
}
#innerid { display:none; }
<a onclick="myFunction(this.href)" href="#innerid">CLICK ME</a>
<div id="outterid">
<div id="innerid">
<p>Hello World</p>
</div>
</div

jQuery click function affecting multiple divs

I'm trying to use jQuery's click function to apply a hover state to a selected div, without differentiating the div's in the JavaScript. I'm currently using:
$(document).ready(function(){
$(".project").click(function() {
$("a.expand").removeClass("hovered");
$("a.expand").addClass("hovered");
$(".project_full").hide();
var selected_tab = $(this).find("a").attr("href");
$(selected_tab).fadeIn();
return false;
});
With the HTML:
<div class="project first project_gizmoscoop">
<div class="title">
GizmoScoop!
<div class="date">2012</div>
</div>
<a class="expand" title="(Caption)" href="#project_1">GizmoScoop!</a>
</div>
<div class="project project_sc">
<div class="title">
Striking Code
<div class="date">2011</div>
</div>
<a class="expand" title="(Caption)" href="#project_2">Striking Code</a>
</div>
The .hovered class is applied to the clicked link (specific styles from an external CSS file). However, everything is being chosen. (See http://www.codeisdna.com for an example).
I know what I'm doing wrong (I should be specifying the individual ID's or using HTML5 data attributes), but I'm stuck unnecessarily. I feel like a complete newb right now, that I can't do something this simple (although I've done more advanced stuff).
You simply need to take advantage of jQuery's flexibility (and good programming practice) and reduce your scope accordingly. You're already doing something similar with your variable definition. For example, to target only those a.expand elements inside the instance of .project that's clicked:
$(".project").click(function() {
$(this).find("a.expand").removeClass("hovered");
...
});
$(".expand").click(function() {
$(this).addClass("hovered");
..
});

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

How to send a form to a javascript function

I need your help to understand how I can send information from a form to a javascript function.
I've created a basic function here : http://jsfiddle.net/nZhR8/5/
The purpose of this function is to hide/display a div.
In fact, I'll have a table with a few contacts (between 0 and 20). There will be a selectlist per contact. For each contact, I'll have to display 1 special div in function of 1 own particularity. So, for contact1, I may have to display div3, and for contact2, display div1.
I'll also use the javascript function to send to the database wich div has to be displayed. It will be a kind of advancement.
If I'm doing it wrong, please tell me why.
I don't see the idea behind this but that could do the trick: http://jsfiddle.net/YCPM7/
That must be a simple draft of a much bigger project.
Also, I would suggest that you either use a common class for each DIVs
<div class="message 1">1</div>
<div class="message 2">1</div>
<div class="message 3">1</div>
...
So you can simply do:
$(".message").hide();
Enjoy.
Firstly, remove the $(...) from where you define the function showDiv, as you don't want to execute showDiv when the page has loaded.
Apart from that, your problem seems to be jsFiddle. It didn't work there, but when I copy+pasted exactly what you posted on jsFiddle into a file, fixed what I mentioned above and tried it in FF, it worked.
There are of course things you can do better about your code, but it works. Suggestions: Give all divs the same class and distinguish them by id, then hide everything with that class and show the one with the correct ID. For the onload, instead of copying the whole code just execute showDiv(1).
You need something like this jsFiddle?
<div id="1" class="1">1</div>
<div id="2" class="2">2</div>
<div id="3" class="3">3</div>
<div id="4" class="4">4</div>
<div id="5" class="5">5</div>
$('div').hide();
$('#StateSelection').change(function() {
var $this = $(this);
$('div').filter('.'+$this.val()).show();
});

Categories

Resources