jquery- onclick find element with same class - javascript

I'm stuck. I have two sets of dynamic elements with a common class (zone and box) and a dynamic class:
<span class="zone dynamicClass1 clickable">Text</span>
<span class="zone dynamicClass6-2 clickable">Text</span>
<div class="box dynamicClass6-2"></div>
<div class="box dynamicClass1"></div>
When you mouseover the <span> "zone", I want to add a class to the <div> "box". Then on mouseleave I want the class to be removed. Thus, something like:
$(document).on("mouseenter",".zone",function(){
$(this + ".the dynamic class").find(".box.the same dynamic class").addClass("hovered");
}).on("mouseleave",".zone",function(){
$(".box.the found dynamic class").removeClass("hovered");
});
The dynamic classes have to be retrieved from the hovered element and then used in finding its match, they cannot be programmed by name. Any help would be great.

The way you have it setup right now, you search for the div inside the span. What you want to do is get the class and then find the according div. I would suggest moving the common class to either an id data attribute, so you can do this:
<span class="zone clickable" id="dynamicClass1">Text</span>
<span class="zone clickable" id="dynamicClass6-2" >Text</span>
var currentClass = $(this).attr("id");
$("div." + currentClass).addClass("hovered");
or this:
<span class="zone clickable" data-class="dynamicClass1">Text</span>
<span class="zone clickable" data-class="dynamicClass6-2" >Text</span>
var currentClass = $(this).data("class");
$("div." + currentClass).addClass("hovered");
See this JSFiddle: http://jsfiddle.net/7v3hd/1/

DEMO
$(document).on("mouseenter",".zone",function(){
var $that = $(this),
classes = $that.attr('class'),
// this is the meat here
// you need to do a string manipulation
// to get the dynamic class out of the
// class attribute. You could also do this
// with regex, or split.
theDynamicClass = classes.replace('zone', '').replace('clickable', '').trim(),
$boxWithSameClass = $(".box."+theDynamicClass);
$boxWithSameClass.addClass("hovered");
$that.one("mouseleave",function(){
$boxWithSameClass.removeClass("hovered");
});
});

You can use;
$(document).on("mouseenter",".zone",function(){
var classes = $(this).attr("class").split(" ");
$("div." + classes[1]).addClass("hovered");
}).on("mouseleave",".zone",function(){
var classes = $(this).attr("class").split(" ");
$("div." + classes[1]).removeClass("hovered");
});
HEre is a working demo: jsfiddle

Related

div#d1 toggle on p#1 click - howTo?

I am trying to toggle a div when its name is clicked.
I have multiple coupls like that in my page, and I want it to work as
"when <p id= "d2"> is clicked => <div id="d2"> is toggled".
I tried those functions:
$(document).ready(function(){
$("p").click(function(){
$("div#" + $(this).attr('id')).toggle();
});
});
function rgt() {
//document.body.innerHTML = "";
var id = "d" + this.id;
var situation = document.getElementById(id).style.display;
if (situation == "none") {
situation = "block";
}
else {
situation = "none";
}
}
function showHide(theId) {
if (document.getElementById("d" + theId).style.display == "none") {
document.getElementById("d" + theId).style.display = "block";
}
else {
document.getElementById("d" + theId).style.display = "none";
}
}
I can't make it Work!!! Why is it?
the browser says:"no 'display' property for null"...
I will be more than happy to solve it with simple jquery
Ensure Your id Attributes Are Unique
Assuming that your id attributes are unique, which they are required to be per the specification:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
You should consider renaming your id attributes to d{n} and your paragraphs to p{n} respectively as seen below :
<button id='p1'>p1</button> <button id='p2'>p2</button> <button id='p3'>p3</button>
<div id='d1'><pre>d1</pre></div>
<div id='d2'><pre>d2</pre></div>
<div id='d3'><pre>d3</pre></div>
which would allow you to use the following function to handle your toggle operations :
$(function(){
// When an ID that starts with P is clicked
$('[id^="p"]').click(function(){
// Get the proper number for it
var id = parseInt($(this).attr('id').replace(/\D/g,''));
// Now that you have the ID, use it to toggle the appropriate <div>
$('#d' + id).toggle();
})
});
Example Using Unique IDs
You can see an interactive example of this approach here and demonstrated below :
Consider Using data-* Attributes
HTML supports the use of data attributes that can be useful for targeting specific elements through jQuery and associating them to other actions. For instance, if you create an attribute on each of your "p" elements as follows :
<button data-toggles='d1'>p1</button>
<button data-toggles='d2'>p2</button>
<button data-toggles='d3'>p3</button>
and then simply change your jQuery to use those as selectors :
$(function(){
// When an element with a "toggles" attribute is clicked
$('[data-toggles]').click(function(){
// Then toggle its target
$('#' + $(this).data('toggles')).toggle();
});
});
Is this you are looking?
$("#p1").on("click", function() {
$("#d1").toggle();
});
js fiddle: https://jsfiddle.net/Jomet/09yehw9y/
jQuery(function($){
var $toggles = $('.divToggle');
var $togglables = $('.togglableDiv');
$toggles.on('click', function(){
//get the div at the same index as the p, and toggle it
$togglables.eq($toggles.index(this)).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="divToggle">Show Me 1</p>
<p class="divToggle">Show Me 2</p>
<p class="divToggle">Show Me 3</p>
<div class="togglableDiv">Weeee 1</div>
<div class="togglableDiv">Weeee 2</div>
<div class="togglableDiv">Weeee 3</div>
Minimal approach using classes. This solution assumes the order of the p elements in the dom are in the same order as the divs are in the order. They do not have to be contiguous, but the order does matter with this solution.
ids are not the droids you are looking for.
An id needs to be unique. If you want to classify something one would suggest to use classes. You can actually use serveral of them for some fancy stuff. How about something like this:
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
Straight forward. Every element that is a switch or switchable gets the class toggle. Each pair of switch and switchable(s) gets an additional identifier (like one, two, ...).
Simple JScript Implementation:
Now how about not using JQuery to work with that? Sure it i$ handy, but it hides all that neat stuff one would eventually like to learn her/himself!
var myToggle = {};
(function(module) {
"use strict";
(function init() {
var elements = document.getElementsByClassName("toggle");
var element;
var i = elements.length;
while (i) {
i -= 1;
element = elements[i].className;
elements[i].setAttribute("onclick", "myToggle.swap(\"" + element + "\")");
}
}());
module.swap = function(element) {
var couple = document.getElementsByClassName(element);
var i = couple.length;
while (i) {
i -= 1;
if (couple[i].style.display === "none" && couple[i].tagName === "DIV") {
couple[i].style.display = "block";
} else if (couple[i].tagName === "DIV") {
couple[i].style.display = "none";
}
}
};
}(myToggle));
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
<p class="toggle two">two</p>
<div class="toggle two" style="display:none">content two 1</div>
<div class="toggle two" style="display:none">content two 2</div>
var myToggle = {} is the object we use to keep our little program contained. It prevents that our code conflicts with other declarations. Because what if some plugin on our site already declared a function called swap()? One would overwrite the other!
Using an object like this ensures that our version is now known as myToggle.swap()!
It may be hard to follow how it got to that name. Important hint: something looking like this... (function() { CODE } ()) ...is called an immediately-invoked function expression. iffy! It's a function that is immediatly executed and keeps its variables to itself. Or can give them to whatever you feed it in the last ()-pair.
Everything else is as verbose as can be... no fancy regular expressions, hacks or libraries. Get into it!

On creating div element give ordered class name

By clicking Create I want to give continuing class name: For example now if you click Create button, it should create the following <div class="div_3">Div 3</div>:
<div id="container">
<div class="div_1">Div 1</div>
<div class="div_2">Div 2</div>
</div>
<input type="button" onclick="add()" value="Create"/>
Here is JS
function add(){
$("#container").append("<div>Div 3</div>")
}
https://jsfiddle.net/5gmr5j8z/
One way is to count the existing elements (and add 1):
$("#container").append("<div>Div " + ($("#container div").length+1) + "</div>");
Simple JSFiddle: https://jsfiddle.net/TrueBlueAussie/5gmr5j8z/2/
You need to apply the same to the class, but this gets a little messy, so neater version below.
You are also better off using jQuery to connect events. Inline event handlers do not have the power of jQuery handlers (and separate event registration from the event handler for no good reason):
$('#add').click(function () {
var count = $("#container div").length + 1;
var $div = $("<div>", {
class: "div_" + count,
text: "Div " + count
});
$("#container").append($div);
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/5gmr5j8z/3/
There are usually neater ways to do this sort of thing, but you need to explain the overall aim first

How to get id's of multiple divs on clicking one div

I have following code
<div id = "fa10_holder">
<div id = "b-1"></div>
</div>
I am adding this dynamically in a div that holds all of these type of divs ..
lets say if I add another div it would be like this
<div id = "fa11_holder">
<div id = "b-2"></div>
</div>
Now the problem is when I click the div with id of b-1 or b-2 and so on I want the id of its parent like fa10_holder and the id of the clicked div aswell... can any one help me ??
Like this working demo another way.
APIs:
parents - http://api.jquery.com/parents/
attr or prop - http://api.jquery.com/attr/ or http://api.jquery.com/prop/
I have added extra class, in case you have many div you can have a blanket click via class. :)
Extra: When to access the attribute (vs the property)?
code
$(document).ready(function () {
$(".hulk").click(function () {
alert($(this).parents('div').attr('id'));
alert($(this).attr('id'));
});
});
html
<div id = "fa11_holder"> parent
<div id = "b-2" class="hulk">hulk</div>
</div>
var thisid = this.id;
var parrentid = $(this).parent().attr('id');

jquery : how to apply same changes inside mulitple container with same class name

i am trying to move a .details outside of .buttons
<div class="product-actions">product 1
<div class="buttons buttons_3 group">buttons
<a class="details" title="Détails" rel="nofollow" >link</a>
</div>
</div>
<div class="product-actions">product 2
<div class="buttons buttons_3 group">buttons
<a class="details" title="Détails" rel="nofollow" >link</a>
</div>
</div>
this do the trick
if ($('.product-actions').length )
{
$('.product-actions').prepend("<div id='new_details_location'></div>");
$(".details").prependTo("#new_details_location");
$('.buttons_3').attr('class','buttons buttons_2 group');
}
the problem is there is more than one product and all a.details get moved to the first product div instead of being prepend at the beginning of each div .product-actions:
http://jsfiddle.net/upKhq/2/
any idea?
Try this FIDDLE
$('.product-actions').each(function () {
$new = $(this).prepend("<div class='new_details_location'></div>");
$(".details", $(this)).prependTo($new);
$('.buttons_3', $(this)).attr('class', 'buttons buttons_2 group');
});
You made a few mistakes:
your selectors were not context sensitive and you were using id in prependTo which has to be unique, but you had 2 divs with the same id.
Did you mean to do this instead?
$('.product-actions').each(function() {
$elem = $("<div class='new_details_location'></div>");
$(this).find(".details").prependTo($elem);
$(this).prepend($elem);
});
$('.buttons_3').attr('class', 'buttons buttons_2 group');
http://jsfiddle.net/samliew/upKhq/4/
You can use each jquery method:
$('.product-actions').each(function() {
var self = $(this);
var new_location = $("<div id='new_details_location'></div>").prependTo(self);
self.find(".details").prependTo(new_location);
self.find('.buttons_3').attr('class','buttons buttons_2 group');
});
And you should not use the same id for two elements.
use .each, and use $(this) to refer to the current .product-actions element. Also you cant have multiple ids that are the same, only the first one would ever be used
if ($('.product-actions').length ) {
$('.product-actions').each(function() {
var newDetailLocation = $('<div></div>');
$(this).prepend(newDetailLocation);
$(".details",$(this)).prependTo(newDetailLocation);
$('.buttons_3',$(this)).attr('class','buttons buttons_2 group');
});
}

jquery, add div with class definition

So I see here how to add a div and here how to add a class but I'm having trouble combining the two. I want to generate a whole bunch of div's with a specific class and id within the div sparkLineContainer.
I have the containing div
<div id="#sparkLineContainer"></div>
and I want to add a bunch of the following to it
<div id="#sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
// and so on
</div>
snippet - I didn't make it very far, I'm stumped
$('#sparkContainer').add("div"); \\ How do I add the id and class to this div?
\\ And as a repeat the function will it overwrite this?
The function I'm trying to do this with.
function renderSparklines (array1, sparkLineName, id) {
// array1 is the data for the spark line
// sparkLineName is the name of the data.
// Turn all array values into integers
arrayStringToInt(array1);
// Create new div of class sparkLines
$('#sparkContainer').add("div")
// Render new spark line to
$('.sparkLines').sparkline(array1, {width:'90px'});
var htmlString = ""; // Content to be added to new div
// GENERATE LITTLE SPARK BOX
htmlString +=
'<font class = "blueDescriptor">' + sparkLineName + '</font>'+
'<br>'+
'<font class = "greyDescriptorSmall">Ship to Shore</font>'+
'<br>'+
'<font class = "blackDescriptorSparkLine">' + array1[array1.length-1] + '</font>'+
'<font class = "greenDescriptorSparkline">(' + (array1[array1.length-1] - array1[array1.length-2]) + ')</font>' +
'<br>';
$('.sparkLines').prepend(htmlString);
}
add does not do what you think it does. You are looking for append or something similar.
You can create the div first and define its attributes and contents, then append it:
var $newDiv = $("<div/>") // creates a div element
.attr("id", "someID") // adds the id
.addClass("someClass") // add a class
.html("<div>stuff here</div>");
$("#somecontainer").append($newDiv);
You need .append or .prepend to add a div to the container. See my version below,
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer")
.append('<div id="id' +
($sparkLines.length + 1) +
'" class="sparkLines">Some Stuff Here</div>')
Also I noticed that you have id of the div as #sparkLineContainer. You should change it as below,
<div id="sparkLineContainer">
...
DEMO
You can add a div or any other tag along with class like:
$('<div/>',{ class : 'example'}).appendTo("p");
Probably the easiest way is to just modify the innerHTML:
$("#sparkLineContainer").append('<div class="sparkLine" id="id1"></div>');
There's other ways as well, but this is the method I generally use.

Categories