I'm sure this is an easy question but I cannot figure it out.
I basically have a div with a number, 'div-1' for example, and need to +1 to the number every time another div is clicked. e.g. 'div-2' 'div-3' etc..
When you say a div with a number, It should be on id attribute.
<div class="your_div_selector" id="div-1">
so, in your javascript, using jquery and when the other div is clicked, just do this:
var div_id = $('.your_div_selector').attr("id")
var new_id = 1 + parseInt(div_id.split("-").pop());
Based on what you've described, it looks like you have an HTML div, which starts with a class of div-1. Every time the div is clicked, you want the div-n class to be replaced with a div-(n+1) class.
This is easily accomplished with an onclick listener.
<div id="mydiv" class="div-1"></div>
<script>
var mydiv = document.getElementById('mydiv');
mydiv.currentClass = 1;
mydiv.addEventListener('click', function() {
mydiv.classList.remove('div-' + mydiv.currentClass);
mydiv.classList.add('div-' + (++mydiv.currentClass));
});
</script>
Note that there should be a better solution, depending on your specific problem.
<div class="yourDivClass" id="myDiv"></div> <button id="incriment" onclick="incrementDivClass()">Click</button>
function incrementDivClass()
{
var divIncriment = ($('.yourDivClass').length);
$('#myDiv').append('<div class="yourDivClass" id="div-'+divIncriment+'">div-'+divIncriment+'</div>')
}
Demo
Related
I have an image gallery that uses modals. In the image modal or outside it, the user can click on a star and mark the image as favorite. Favorite images have a class that makes the star change color its to 'golden'. If a user marks a favorite in the modal, I need to change the color of the star of that image outside the modal as well.
To do this, I thought I could have a
<p id = "modal_counter" class = "hidden">number</p>
in the modal, so that I can get the image number. Then I use that image number as part of a jquery selector.
The images in the gallery have something like this:
<p id = "image_number" class = "hidden"></p>
<!-- for example: <p id = "image_2" class = "hidden"></p> -->
So, all I need is to successfully select the hidden p tag next to each image, then I could use jquery's next() or parent().find().
This is the relevant code:
...
var modal_counter = div_parent.find('#modal_counter').text();
var counter = "#image_"+String(modal_counter);
/* I would like the counter to be something like "#image_2" */
var $(counter).parent().find('.star').addClass('golden')
...
This doesn't work. Jquery tries to find an object using this selector:
"#image_\n 2"
and of course, it doesn't find one. I tried removing the \n with a regex, but it still doesn't work:
counter_processed = modal_counter.replace(/(<([^>]+)>)/ig,"");
It'll probably be better to use a data-attribute on your element rather than getting the text content. Do:
<p id = "modal_counter" class = "hidden" data-counter="number">number</p>
Then you can:
...
var modal_counter = div_parent.find('#modal_counter').data('counter');
var counter = "#image_" + modal_counter;
/* I would like the counter to be something like "#image_2" */
var $(counter).parent().find('.star').addClass('golden')
...
This way you don't bind your javascript to the text inside your elements.
jQuery has a handy trim function:
var modal_counter = div_parent.find('#modal_counter').text().trim();
Try this from your console:
$.trim("\n\nHello\r\nThere\n")
See how it removes the leading and trailing white-space?
Let's say you have:
<p id="modal_1" class="hidden">Img 1</p>
you can extract the number both using:
// If you need it from the text
var n = $("[id^=modal_]").text().match(/\d+/); // 1
or
// If you need it from the ID
var n = $("[id^=modal_]")[0].id.match(/\d+/); // 1
Than to target the image like:
<img id="image_1" src="someimage.jpg" alt="SEO">
you do:
$('#image_'+ n)
If you really just have:
<p id="modal_counter" class="hidden">3</p>
than you can do:
var n = $('#modal_counter').text(); // "3"
$("#image_"+ n) // .fadeIn() or whatever...
Just make sure you don't have duplicate modal_counter ID elements on your page. ID has to be unique.
I have a loop that display buttons with class name that has javascript on it. I need to pass the id of span that is clicked. My problem is because of the loop there, I can get the ID by its index but what I want to get is the id of the clicked button dynamically.
while(...){
<span class="id">'.$table["id"].'</span>
<input type="button" class="edit" value="Edit"/>
}
$('.edit').on('click', function (e) {
var x=document.getElementsByClassName("id")[0];
var xx = x.innerHTML;
$.fancybox({
...
}
});
});
sounds like you want to use
var x= $(this).closest("span");
that should get you the span next to the button clicked.
Could you use just $(this). within your click event?
You don't need to do this:
var x=document.getElementsByClassName("id")[0];
just say
var x = $(this);
because you are already on your element there, when the click event happens.
Hope it helps! :)
I would go with data attributes for passing variables, so you can leave classes for css style purposes only. Also if you are already using jQuery why not going all the way with it?
while(...){
<span class="id" data-id="id">'.$table["id"].'</span>
<input type="button" class="edit" value="Edit" data-target="id"/>
}
$('.edit').on('click', function (e) {
var data = $(this).data('target'); // Get the data-target attribute
var target = $('*[data-id='+data+']'); // Find the matching span
var xx = target.html(); // Get HTML from Span
$.fancybox({
...
}
});
});
I'm creating a directory of apps, each of which has it's own comments which are hidden until the user opens them. I'd like to show the number of comments that each app currently contains but I can only get it display the total number of comments on the page (See JSFiddle: http://jsfiddle.net/9M4nw/2/ for a basic example). Ideally it should display 2 in the top box and 4 in the bottom box. I thought I might need to use an array or something along those lines?
Here is my code:
HTML
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
jQuery
$(".parent").each(function(index){
var numChilds = $(".child").length;
$(".parent").append(numChilds);
});
You have to select the current HTML element (with class parent). Then, you will use it in selecting the length of elements with class .child and the html for .counter.
Using $(this) you can select the current HTML element from each() function.
Corrected code:
$(".parent").each(function(){
var numChilds = $(".child", $(this)).length;
$(".counter", $(this)).html(numChilds);
});
JSFIDDLE
The problem is you need to limit the scope of the element look up to the desired parent element
$(".parent").each(function(index){
var numChilds = $(".child", this).length;
$(".counter", this).html(numChilds);
});
Another version
$(".parent").each(function(index){
var $this = $(this);
var numChilds = $this.find(".child").length;
$this.find(".counter").html(numChilds);
});
Demo: Fiddle
This would require some extra work to show the number of childs in a more elegan way, but it should be enough to understand the idea
$(".parent").each(function(index){
var $this = $(this);
var numChilds = $this.find(".child").length;
$this.append("<span>" + numChilds + "</span>");
});
This code will help you to get number of children separately for each parent div :-
$(document).ready(function () {
$(".parent").each(function (i) {
$(this).children().length;
});
});
Try this hope this may help you.Vote
GetElementById works if I manually added a div id="something" inside the body and use window.onload = init method in the script to get it. Works great.
But if I used a for loop to generate divs where id's is 1,2,3 and so on. I can't get it. Is there a way to get to those generated divs?
This is what generates the html code (just to be clear what I mean):
for(i=0; i<randomizeColoursList.length; i++)
{
document.getElementById("renderColors").innerHTML +=
'<div class=\"box\"><div class=\"' + i + '\"><font color=\"'
+ randomizeColoursList[i] + '\">'
+ "" + '<img src=\"dist/card_bg.gif\"></div></div>';
}
Generates one of these:
<div class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Div with class 8 is the id I want to get for example. But is says it's null.
Thanks.
The id is null because you haven't specified it in your markup creation. Looks like you're assigning the id value to class instead.
Generate something more like this:
<div id="div1" class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>
Also, you don't need to use font tags, nor should you use them. Just add the styling to the div.
<div id="div1" class="8" style="color:#3be6c4;"><img src="dist/card_bg.gif"></div>
The way you're going about this is a little backwards. If you write your code like I have below, then you don't need to give the divs IDs, you end up with an array full of references to them anyway.
var i, div, img;
var createdDivs = [];
for(i=0; i<randomizeColoursList.length; i++)
{
div = document.createElement('div');
img = document.createElement('img');
div.className = "box";
div.style.backgroundColor = randomizeColoursList[i];
div.style.color = randomizeColoursList[i];
img.src = "dist/card_bg.gif"
div.appendChild(img);
document.getElementById("renderColours").appendChild(div);
createdDivs.push(div);
}
Live link: http://jsfiddle.net/7HjLL/
So I want to get the first <a> tag in this <div>. This is really driving me nuts. Thanks for any help.
HTML
<div id="PGD" class="album" onmouseover="load(this)">
<a class="dl" href="#">DOWNLOAD</a>
</div>
Javascript
function load(dl)
{
var ID = $(dl).attr('id');
var elemnt = $('ID:first').attr('id');
}
Non-jQuery: (was not tagged with jQuery before, so I included this)
If you want to get the first child element only:
var element = document.getElementById('PGD').children[0];
If you want to get the first anchor element:
var element = document.getElementById('PGD').getElementsByTagName('a')[0];
With jQuery:
var element = $('#PGD').find('a:first');
// or, to avoid jQuery's pseudo selecors:
// var element = $('#PGD').find('a').first();
and actually your function can just be
function load(dl)
{
var element = $(dl).find('a:first');
}
Update:
As you are using jQuery, I suggest to not attach the click handler in your HTML markup. Do it the jQuery way:
$(function() {
$("#PGD").mouseover(function() {
$(this).find('a:first').attr('display','inline');
alert($(this).find('a:first').attr('display'));
});
});
and your HTML:
<div id="PGD" class="album">
<a class="dl" href="#">DOWNLOAD</a>
</div>
​See for yourself: http://jsfiddle.net/GWgjB/
$("#PGD").children("a:first")
This will give you the first child "a" tag, but not the descendents. E.g.
<div id="log">
<p>Foo</p>
Hello
Hello
</div>
Will give you : Hello
$(ID).find(':first')
See find jQuery command.
$('#PGD').find('a:first')
Actualy I've not understanding problem, so I'm trying correct your function, to make it clear for you:
function load(dl)
{
// var ID = $(dl).attr('id');
// var elemnt = $('ID:first').attr('id'); // Here is error-mast be like $(ID+':first')
var ID = $(dl).attr('id');
var elemnt = $(ID).find('*:first').attr('id');
}
I supose dl that is $('#PGD'). But child element A have not attribute id, what are you trying to find?
Also See: http://api.jquery.com/category/selectors/