I've bene bursting my head for the last few hours. Here's the situation:
I have a website that has many divs, but many of them share classes (they are equal) but have some different texts. Example:
<div class="summary-title">
I Am That Girl</div>
<div class="summary-title">
I Am That Girl</div>
What I want to do is select each one of these divs and add a span whenever another div is hovered.
I mean, this is what I want to do: hover a div that's before the sumary-title div, a span with a class is appended inside the sumary-title div or out of it, whatever works.
That's what I got so far:
$('summary-title').each(function(index) {
var content = $(index).next().text();
$(index).append("<span class='hover-text'>"+content+"</span>");
});
But I get an error that $ is not defined, probably because it is a closure?
I have no idea what to do. The code seems horrible too — i need to do this quickly and I just can't do. Would anyone help me at least know what to do?
Thanks
append() is already an implicit iteration ( that loops through the set of elements in the jQuery collection.) and it's unnecessary to call .each() .
$('.summary-title').append(function() {
return "<span class='hover-text'>" + $('a', this).text() + "</span>";
});
Outside of making sure you have jQuery on your page and properly referring it, your code should go like:
$('.summary-title').each(function() {
var content = $(this).children('a:first').text();
$(this).append("<span class='hover-text'>"+content+"</span>");
});
Notice:
dot in class selector - $('.summary-title')
this instead of index - $(this)
children selector instead of next
Check demo - Fiddle.
To append this to a preceding element on hover use:
$(document).ready( function() {
$('.summary-title').hover( function() {
var content = $(this).children('a:first').text();
$(this).prev().append("<span class='hover-text'>"+content+"</span>");
});
});
Related
I've got an FAQ page I'm building. Next to the question, there is a plus sign to expand the content. On click, I've added the class active, but there are many questions, and I don't want to repeat the same jQuery snippet for each question. I've figured out how to find the parent ID but I'm having trouble storing it in an variable to reuse in the jQuery script.
What I want to be able to do:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$('element .expand').toggleClass('active')
})
Is there a way to do this? I get undefined when I do this:
$('.expand').click(function(){
console.log(element)
});
You can use the find() function to locate children of a selected element:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$("#" + element).find('.expand').toggleClass('active')
});
However, looking at your code, it seems like you just want to toggle the "active" class of the clicked element. If that is the case, you can do this much more simply without a variable at all:
$('.expand').click(function(){
$(this).toggleClass('active')
});
Think of the following HTML code to apply Jquery:
HTML code:
<div id="outer_div">
<div id="inner_div_1"></div>
<div id="inner_div_2"></div>
<div id="inner_div_3"></div>
</div>
By default, the "outer_div" is hidden. It appears while clicked on a button using Jquery show() function.
I wanted to do the following: On click within anywhere of "outer_div" excluding the area within "inner_div_1" , the "outer_div" would again be hidden. I failed while tried the following codes. What should I amend?
Attempted Jquery 1:
$("#outer_div:not(#inner_div_1)").on("click",function(){
$("#outer_div").hide("slow");
});
Attempted Jquery 2:
$("#outer_div").not("#inner_div_1").on("click",function(){
$("#outer_div").hide("slow");
});
Your support would be highly appreciated.
You need to consider that a click in the inner div is also a click on the outter div. That being said, you just need to check the target and target parents :
$("#outer_div").on("click",function(e){
if(!$(e.target).closest('#inner_div_1').length) $("#outer_div").hide("slow");
});
You can use some of the data in the event
$("#outer_div").on("click",function(e){
if( // Fast check to see if this is the div
e.target.id !=='inner_div_1'
// We limit the 'closest()' code to the outer div. This adds children to the exclude
&& $(this).closest('#inner_div_1, #outer_div')[0].id=='outer_div'){
alert('good click');
}
});
This is a solution for your code now, this works perfect when not too many excluding objects. But no wildcard selectors, which is nice.
And a jsFiddle demo.
Other properties can be used to, like a class:
$("#outer_div").on("click",function(e){
if( e.target.className!=='even'
&& $(this).closest('.even, #outer_div')[0].id=='outer_div'){
alert('yay, clicked an odd');
}
});
I made 7 lines, gave the even ones a class 'even'.
I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).
I see that this has been asked many times. But, unfortunately I have not come across a straight forward solution. Most solutions revolve around multiple nodes within the div.
So here's problem. I have the following markup:
<div class="test">Text1<span></span></div>
I need "Text1" to be replaced with "Text2" without affecting the span tag and event handlers attached to the span tag.
Doing something like $('.test')html('Text2<span></span>') does replace the text. But, removes the event handlers on the span tag, which is not desired. I am looking for a quick and efficient method for this one.
Wrap replaceable text with a tag:
<div class="test"><span class="test-text">Text1</span><span></span></div>
You can access the Text Node itself with contents. Now if you know that the element starts with text you can do this:
$($('.test').contents()[0]).replaceWith('New Text');
Now if you didn't know the location in the array of the Text Node, you can filter with:
return this.nodeType === 3;
and compare the text values (if you know those).
Fiddle
if you would add event handler with .live or .on functions (depends on jQuery version) .html('Text2') would work just fine.
On the assumption that the text to be replaced will always precede the existing span, that it will always be the firstChild and that it will be an unwrapped textNode:
$('.test').click(
function() {
this.firstChild.nodeValue = 'Text2';
});
JS Fiddle demo.
To ensure that only the first textNode is changed, regardless of where it's found within the .test element:
$('.test').click(
function(e) {
var newText = 'Text2',
children = e.target.childNodes;
for (var i=0,len=children.length;i<len;i++){
if (children[i].nodeName == '#text'){
children[i].nodeValue = newText;
return false;
}
}
});
JS Fiddle demo.
I'm trying to change the alt of the image, I'm clicking by
selecting the image's class (add_answer)
Note: .add_answer shows up multiple times inside different containing div's
jQuery(function(){ // Add Answer
jQuery(".add_answer").click(function(){
var count = $(this).attr("alt");
count++;
$('.a_type_'+count+'').show();
$(this).parents("div:first").$('.add_answer').attr("alt", count);
});
});
This line doesn't seem to be working, how do I select this add_answer class by way of it's parent div
$(this).parents("div:first").$('.add_answer').attr("alt", count);
Anyone else have an idea?
I'm trying having trouble decreasing the alt value on the .add_answer image when .destroy_answer is clicked
jQuery(function(){ // Hide Answer
jQuery(".destroy_answer").click(function(){
$(this).parents("div:first").hide();
var count = $('.add_answer').attr("alt");
count--;
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
});
});
Problem line:
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
you can use the parent div as the scope:
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
This should work:
$(this).parent("div").find(".add_answer").attr("alt", count);
You code is almost correct. Required change is to use .find instead of .$ after .parents method. Use of .parent instead of .parents should be avoided, this way your code will be more unobtrusive (precisely - this way img can be non-direct child of the div).
$(this).parents('div:eq(0)').find('.add_answer')
You can manipulate :eq(0) to select eg third parent div using :eq(2).