Using "this" with jQuery Selectors - javascript

I have some HTML that looks like this:
<ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
Using CSS I'm setting the p tag to display:none;. I want to use jQuery to display or hide the p tag when the anchor is clicked, but I'm having some troubles with the sibling selector.
Just trying to get the selector working, I tried:
$("a.question").click(function () {
$(this + " ~ p").css("background-color", "red");
});
to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen.

Try using:
$(this).siblings('p').css()

$(this).next("p").css("...")
the "p" above is optional, if you just want the next non-whitespace node in the DOM.

I want to use jQuery to display or hide the 'p' tag when the anchor is clicked
Since you mentioned that you'd like to toggle the 'p' tag when the anchor is clicked, I'd do:
$("a.question").click(function (event) {
$(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element
event.preventDefault(); //stop the browser from following the link
});

Related

How to get which link was clicked in jQuery

I want to get the text $(el).text() from a block of multiple links and assign it to HTML input.
I'm using Laravel and Jquery.
My Blade template is a separate component that is generated from some data.
<div class="some-class" id="some-id">
<ol>
#foreach ($data as $el)
<li>
{{ $el['name'] }}
</li>
#endforeach
</ol>
</div>
Then I'm looking at how to catch the click of the link, get the text from it, and pass it to the input.
My jQuery code looking like:
$('#some-id > a').on('click', function () {
console.log(this.text());
})
From multiple sources found that the way above ^ should be working, but for me, it doesn't even understand that I have clicked.
Maybe is there another way to get the clicked link name?
Thank you.
Change your jquery selector to this:
$('#some-id ol li a')
Right now you are trying to select a elements that their parent element is #some-id, which is not the case. There is a difference between Children of an element (div > p) and Descendants of an element (div p).
The #AlwaysHelping comment was the one I was looking for.
$(document).on('click', '#some-id a', function () {console.log($(this).text());})

Using jQuery to realize a click event for a span without using ID and Name

How to use jQuery to click the span tab like below?
like this:
<span data-bind="event: {click: toggleshow}, css: {open: more()}" class="">
Expand<span></span>Search</span>
You can add a css class to your span and use the css class as your jQuery selector for registring the click event
<span class="myspan" id="someId">Test</span>
<span class="myspan" id="someOtherId">Test Again</span>
And the jQuery code will be
$(function(){
$("span.myspan").click(function(e){
alert("clicked");
var itemId=$(this).attr("id");
alert(itemId);
});
});
Here is a working sample
If you cannot add a css class or other attributes to this span, you might need to use a very wide jQuery selector, which is just the span tag.
$("span").click(function(e){
alert("clicked");
});
But this click event will be registered to all span's in your page. Another option is to wrap these spans inside a container div and use that in your jQuery selector so that only those span's will be registered for the click event.
<div id="myContainer">
<span data-bind="event: {click: toggleshow}, css: {open: more()}" class="">
Expand<span></span>Search</span>
</div>
And the jQuery code to register the click event will be
$(function(){
$("#myContainer span").click(function(e){
alert("clicked");
});
});
Here is a working sample of that.
jQuery can take pretty much any CSS selector.
So if you don't want to use a class or an id (which you should), there are 2 options:
Read up about CSS selectors and find an appropriate one.
Open
the inspector tools in your browser, right click on your span
element in the HTML view and choose the option "Copy Unique
Selector" (Firefox) or "Copy > Copy selector" (Chrome) to get an
automatically generated selector for your element.
Then use it normally with jQuery: $("copy_pasted_probably_very_long_selector").click()
1st: in html use
</span><span>Search</span>
instead of
<span></span>Search</span>
2nd: while you tagged javascript/Jquery for click event so you can use .filter()
$('span').filter(function(){
return $(this).text().trim() == 'Expand';
}).on('click' , function(){
//code here for Expand span
});
Working Demo This will work with Expand span .. use the same way for Search one
You can use the event object to find the nodeType .Here is a snippet to illustrate it
HTML
<span class="item-content">Button 1 </span>
<span class="item-content">Button 2 </span>
<div class="item-content">Button 3 </div>
<button class="item-content">Button 4 </button>
JS
$('body').on('click',function(event){
alert(event.target.nodeName)
})
event object have many other keys which can also come handy when required.You can just console.log(event) so see others keys.
WORKING MODEL
NOTE: I used multiple tags just for demonstration. Also though each element have a class but I used it just for styling.
Hope this will be useful

Find element above another using jQuery

I'm trying to find the element using jQuery from the following html.
<ul class="gdl-toggle-box">
<li class="">
<h2 class="toggle-box-title"><span class="toggle-box-icon"></span>Volunteer Form</h2>
<div class="toggle-box-content" style="">
</div>
</li>
</ul>
What I'm looking to do is when the h2 is clicked find the li above the h2 add a class active to it. Tried a few different calls but no luck.
EDIT
The biggest issue is that there are multiple toggle boxes on a page so something like this works on pages with a single toggle but pages with multiple the result is they all open together.
var gdl_toggle_box = jQuery('ul.gdl-toggle-box');
gdl_toggle_box.find('li').each(function(){
jQuery(this).addClass('item');
});
gdl_toggle_box.find('li').not('.active').each(function(){
jQuery(this).children('.toggle-box-content').css('display', 'none');
});
gdl_toggle_box.find('h2').click(function(){
if( jQuery('.item').hasClass('active') ){
jQuery('.item').removeClass('active').children('.toggle-box-content').slideUp();
}else{
jQuery('.item').addClass('active').children('.toggle-box-content').slideDown();
}
});
You can use closest.
closest will match the first parent element that matches the selector traversing up the DOM tree.
Demo
$('h2.toggle-box-title').click(function(){
$(this).closest('li').addClass('active');
});
Try this.
$('h2.toggle-box-title').click(function(){
$(this).parent().addClass('newclass');
});
try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
On you click in the button you can use the event:
$("something").parent().find("h2.myClass");
// And if you want you can add class after you find you object
http://api.jquery.com/find/
Selecting an element's parent
In order to select an element parent, you can use the parent() function.
Try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
*to be more specific, you target the parent you would like to choose by specifying its selector
Check the jQuery API Documentation here
parent() - Get the parent of each element in the current set of matched elements,
optionally filtered by a selector.

Remove class from element and add to next element

I have a list of links, one has the class active.
On my next button click id like to remove the class from the current element and add it to the next only I cant seem to get it to add?
Ive made a fiddle to hopefully explain my problem, any help would be great, thanks
http://jsfiddle.net/h6D4k/
$('.next').click(function(){
$('ul.pagination').find('a.active').removeClass('active');
$('ul.pagination').find('a.active').next('a').addClass('active');
return false;
});
One of the jQuery most usable conveniencies is that its methods are (usually) chainable - in other words, they return the very object they are called from. So you can simply write this:
$('ul.pagination').find('a.active').removeClass('active').closest('li')
.next('li').find('a').addClass('active');
... as it's <li> elements that should be 'nexted', not <a> ones. But in fact, you shouldn't probably discard 'active' altogether if it's the last element in question:
var $a = $('ul.pagination').find('a.active'),
$li = $a.closest('li'),
$nextLi = $li.next('li');
if ($nextLi.length) {
$a.removeClass('active');
$nextLi.find('a').addClass('active');
}
This is actually what you want based on your html structure in you fiddle. http://jsfiddle.net/h6D4k/1/
$('ul.pagination').find('a.active').removeClass('active').parent()
.next().find('a').addClass('active');
Because once you've done this...
$('ul.pagination').find('a.active').removeClass('active');
There is no more a.active - the active classname has been removed from that element. So repeating the same selector...
$('ul.pagination').find('a.active')//...
... will select nothing.
Chain it all together instead.
$('ul.pagination').find('a.active').removeClass('active').next('a').addClass('active');
You have a second problem. According to the jQuery API for next(), it will:
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
You're not trying to get the following sibling:
<ul class="pagination">
<li><a class="one active" href="#">X</a></li>
<li><a class="two" href="#">X</a></li>
<li><a class="three" href="#">X</a></li>
</ul>
Next
Prev
You're trying to get the next <a> in the whole document. That's more challenging - and I'm not sure how to do it.
I would write it this way, preventing the action from doing anything on the last li as well.
http://jsfiddle.net/h6D4k/6/
$('.next').click(function(e){
e.preventDefault();
if ($("ul.pagination a.active").parent().is(":last-child")) return;
$('ul.pagination a.active').removeClass('active').parent().next().find("a").addClass('active');
});
You have two errors in your code:
Once removed, the active class can't be found anymore
your a tags are nested in li tags so next() doesn't work as you expect
To simplify things, you could attach the active class to the li tags.
Live demo: http://jsfiddle.net/h6D4k/7/
Code:
$('.next').click(function(){
$('ul.pagination').find('li.active').removeClass('active')
.next().addClass('active');
return false;
});

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.

Categories

Resources