jQuery - Display occurrence number of divs - javascript

I have the following html...
<div class="display">sometext</div>
<div class="display">sometext</div>
<div class="display">sometext</div>
Using jQuery I want to be able to click the first div and an alert is displayed saying that you have clicked the first div and so on. I know how to count the number of divs with a specific class but not how to tell which one is clicked.

Behind the scenes, .index() also loops through all previous elements. The following alternative is more efficient than .index() when the element has lots of siblings.
$(".display").each(function(i){
$(this).click(function(){
alert("Clicked div.display, number " + i);
}
});

I'm not sure about 'first' as such, but you could try:
$('.display').click(
function(){
alert("You clicked div number: " + ($(this).index('.display') + 1) + ", of " + $('.display').length);
});
JS Fiddle.
References:
.index().

Here's a simple way.
$divs = $('.display');
$divs.click(function(){
alert( $divs.index($(this)) );
})
Fiddle to go with it.

The answer is simple and proven by this jsfiddle:
var containers = jQuery('.display');
containers.bind('click', function(event){
alert('Clicked element no. ' + (containers.index(this)+1));
});
Please let me know if it helped.

You can do just:
HTML
<div class="display" name="1">sometext</div>
<div class="display" name="2">sometext</div>
<div class="display" name="3">sometext</div>
JavaScript
$('.display').click(function(){
alert($(this).attr('name'));
});
Demo : http://jsfiddle.net/SzwJU/

Why use jQuery? You can write a simple javascript that is triggered onclick by the div.

Related

Javascript append + click remove them

I got a question, what I have already solved, but it's just so annoying.
I have a js code, which is putting down some html code when a button is pushed with "append", and with that code I'm giving an id to an x button, and an id to the container element. I wanted to use these id-s to identify them with a click function, to remove the html code:
var num = 0;
$('.button').click(funcion(){
num++;
var code = '\
<div class="container" id="text' + num + '">\
<div id="x' + num + '">\
x\
</div>\
Some stuff\
</div>\
';
$('.puthere').append(code);
$('#x' + num).click(function(){
$('#text' + num).remove();
});
});
Now the annoying part is the click function on the x. What I would expect is, that this code would work somehow like this:
1st click on the "button" class element should give this code:
$('#x1').click(function(){
$('#text1').remove();
});
after 2nd click I should have this:
$('#x1').click(function(){
$('#text1').remove();
});
$('#x2').click(function(){
$('#text2').remove();
});
instead what I'm getting after the 2nd click is this:
$('#x1').click(function(){
$('#text2').remove();
});
$('#x2').click(function(){
$('#text2').remove();
});
so it's always the last element what the x buttons want to remove. My question is, why can my "num" variable stay "1" at the #x1, but not at the #text1?
My solution was to address the parent element instead:
$('#x' + num).click(function(){
$(this).parent('.container').remove();
});
I know, that there is the "live" function too, what I could use, and I wouldn't need to mess with id-s, but that just seems more heavy. Is that correct? Or I'm overcomplicating things too much without making it more efficent?
It's because num is global and you access it after you create second button. To fix this you can wrap your code with anonymouse self executing function:
(function(num) {
$('#x' + num).click(function(){
$('#text' + num).remove();
});
})(num);
or better use only one click
$('.parent').on('click', '.container > div', function() {
$(this).parent().remove();
});

Select DIV using its ID + addition

Using a div as selector is easy:
<div id="test1"></div>
$('#test1').doSomething();
I want to target only another div, containing the same ID + _sub:
<div id="test1"></div>
<div id="test1_sub"></div>
$('#test1').find( /* Same ID + "_sub" */ ).doSomething();
How can I do this? I know I can use .attr('id') to take #test1, but I do not how to extend this with _sub.
JS FIDDLE
Of course it would be easy to target the #test1_sub directly, but image I have 1000 divs counting up test1, test2, test3, etc. and want to use this inside of a function.
You do it like this
$('#test1' + "_sub").fadeOut();
Note the quotation-marks containing "_sub".
EDIT: In your answer, you made up an example where you had 100 divs with ids like test1, test2 and so on. Then you could select all elements with an id beginning with test. Like this:
$('*[id^="test"]').fadeOut();
Here you can use start with selector to work with all ids.
jsFiddle
$(document).ready(function(){
$( "*[id^='test1']" ).fadeOut();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test1_sub"> Test 1 Sub</div>
<div id="test1_asdf">Test 1 ASDF</div>
<div id="test1_sub342"> Test 1 sub342</div>
<div id="test1_sdfsd">Test 1 sdfsd</div>
<div id="test1_45645"> Test 1 45645</div>
Set a variable and chain: (CORRECTED)
var target = $(whatever test div you targetted).attr('id');
$('#'+target + "_sub").doSomething();
You said you were going to use it in a function, so it would be targettable this way for example. Lets say when you click #test1 a function will run on all subs based on the clicked test:
$('.testBoxes').click(function () {
var target = $(this).attr('id');
$('#'+target + "_sub").doSomething();
});

Getting all colors from a div with jQuery/JS

Is it possible to get all colorvalues that exist in a div with a certain class, and its child elements?
for example, i have:
<div class="row client">
Link1
<span style="color:#f3f3f3;">Span</span>
<h3 style="color:#ff00ff;">Subtitle</h3>
</div>
I want an array to get all colors:
background of the parent div
color of the <a> element
color of the <span> element
color of the <h3> element
Also, i'm using highcharts to display charts in the same div. Is it possible to get the colors used there aswell?
I don't think i can put this any clearer for you guys,
Many thanks!
Job
You can use:
var colorarray=[];
$('.client').children().addBack().each(function(){
if(!$(this).is('.client'))
colorarray.push("color of the <" +$(this).prop("tagName")+"> is "+ $(this).css('color'))
else
colorarray.push("background of <" +$(this).prop("tagName")+"> is "+ $(this).css('backgroundColor'))
})
Working Demo
If you want the color in hex, you can refer this https://stackoverflow.com/a/1740716/1719752
You can just loop through all the elements in the div
Fiddle
var elements = $(".client").children()
$(elements).each(function(index) {
console.log( index + ": " + $(this).css("color"));
});
Here’s a rather inefficient but, I think, easy to understand approach without libraries:
let allNodes = Array.from(document.querySelectorAll('*'));
let setOfColors = allNodes.reduce((colors,el) => {
return colors.add(getComputedStyle(el).backgroundColor)
}, new Set)
let arrayOfColors = Array.from(setOfColors);

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 can I add my own <divs> to a container dynamically?

I found a lot of info about this, but I haven't foundanything that could help me yet.
My problem is that I have got a div with its id and it supposes to be a container (#cont_seguim).
I have a menu on the right side which contains circles (made by css and filled with text), like following:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
where b and n are the format for background and text.
When I click a circle, this one must be added to the container (notice that each circle has got its own text), but I can't get that.
I made and array and used alert() to test that click works, and it does, but append() doesn't even work to print text, and I don't know why.
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
Thank you for your responses!
Your code seems to work fine (if you fix the different class name used in html vs script circulo_menu vs circle_menu)
Demo at http://jsfiddle.net/7jbUj/
To add the whole circle append the whole element and not its text by using .append(this)
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
Demo at http://jsfiddle.net/7jbUj/1/
To add a copy of the circle, so you can add multiple of them use the .clone() first..
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
Demo at http://jsfiddle.net/7jbUj/3/
Inside the click handler, this refers to the clicked element. And since you bind the click handler on the circle_menu element, this refers to that. You can use it directly for the appending or clone it to make a copy first..
unable to understand properly, hope below one can help you.
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
make sure classname and id name will remain same as html
Try using html() instead of text().
Try this: Demo
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
Try this:
$( ".container" ).append( $( "<div>" ) );
source
use
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
You could try
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
By this way the clicked circle element get added to div

Categories