jQuery/JS - Count elements within element - javascript

In jQuery or JS I need to count the amount of DIV elements inside my parent DIV called cont? I've seen similar questions here on StackOverflow and have tried the following.
<div class="b-load" id="cont">
<div>
<img src="page2.jpg" alt=""/>
</div>
<div>
<img src="page3.jpg" alt="" />
</div>
<div>
<img src="page4.jpg" alt="" />
</div>
<div>
<img src="page5.jpg" alt="" />
</div>
</div>
function countPages() {
var maindiv = document.getElementById('cont');
var count = maindiv.getElementsByTagName('div').length;
alert(count);
}
The child DIV's are dynamically produced, so I need to count them after the page has finished loading. The problem I have is the function I wrote counts 13 DIV's and in this example, there should only 4!! Any help gratefully received..

console.log($("#cont div").length);

var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);

Try this
$(function(){
var mainDiv = $('#cont');
var childDivCount = mainDiv.find('div').length;
});
By the way, this is jQuery's syntax (one of them anyways) for document ready. This will only fire after your page has completed loading.

No need to use jQuery here. If you only need to know the amount of childElements, you can use node.childElementCount

Related

Ascertain the position within a list of elements of the parent of a clicked element

I have a list of elements similar to simplified HTML below. When one of the images is clicked some JavaScript if fired, and the image that is clicked becomes this.theImage.
I now need to get the position of the image; for example if the first image was clicked, the position should be 1, if the second is clicked it should be 2, and so on.
I could use var elements = $('.image-preview', '#gallery');, to take a list of all elements with the image-preview class, and then loop through them and match the ID to the image, but that seems really inefficient.
Is there another way of achieving this task that is more efficient?
<div id="gallery">
<div class="image-preview">
<img id="image-1" src="http://www.mysite.com/image1.jpg" />
</div>
<div class="image-preview">
<img id="image-2" src="http://www.mysite.com/image2.jpg" />
</div>
<div class="image-preview">
<img id="image-3" src="http://www.mysite.com/image3.jpg" />
</div>
<div class="image-preview">
<img id="image-4" src="http://www.mysite.com/image4.jpg" />
</div>
</div>
Not sure I get it, you catch a click on the image like this
$('.image-preview img').on('click', function() {
});
and then to get the index you'd do
$('.image-preview img').on('click', function() {
var index = $('.image-preview img').index(this);
});
note that it's zero based
FIDDLE
You can make Array.prototype.indexOf do it for you:
var gallery = document.getElementById('gallery'),
els = [].slice.call(gallery.getElementsByTagName('img'));
gallery.onclick = function(e) {
if(e.target.tagName.toLowerCase() !== 'img') return;
var position = els.indexOf(e.target);
};
Demo

get element id when scroll to it

I have a website for read comic online.
HTML of read page is:
<div id="listimages">
<img src="abc1.jpg" id="image1" />
<img src="abc2.jpg" id="image2" />
<img src="abc3.jpg" id="image3" />
<img src="abc4.jpg" id="image4" />
</div>
I want to get the id of the image being scrolled to.
Example when I'm viewing img abc2.jpg I want get element id of it is #image2.
idnow = idnow_getted
Please help me, thanks everybody !
You can compare the window's scrolltop and image's top position to get the id of the image which is scrolled to.
For ex,
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $imgs = $('img');
$.each($imgs, function(item) {
if($(item).position().top <= winTop)
//get id here
});
});
There may be two scenario in which you you want id of image and do further processing,
First scenario You want execute something on scroll of window.
In this case just add a handler on scroll event.
$(window).scroll(function() {
var windowTop = $(this).scrollTop(),
image = $('#listimages').find('img').filter(function(){
return $(this).offset().top < windowTop+100;
//i am adding 100 in windowTop as we can consider the the image as cuurent image even if it is little bit below than top of window.
});
//now you can directly use image if you want to manipulate it.
//if you want id you can get it by
var id=image[0].id //or image.attr('id');
});
Second scenario , if you want to perform some action on trigger of any event.
function currentImg(){
var windowTop = $(this).scrollTop(),
image = $('#listimages').find('img').filter(function(){
return $(this).offset().top < windowTop+100;
});
return image[0].id;
}
But remember adding events like scroll,mousemove are executed more often so they are suggested not to use much until you need it much .
Just Try with the following,
JavaScript and jQuery Part :
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#listimages img').mouseover(function() {
alert(this.id);
});
});
</script>
HTML Part :
<div id="listimages">
<img src="abc1.jpg" id="image1" />
<img src="abc2.jpg" id="image2" />
<img src="abc3.jpg" id="image3" />
<img src="abc4.jpg" id="image4" />
</div>
I think this may help you to resolve your problem.

If image width is less than X, add class

As the title suggests, I'm looking to have a little bit of jQuery - if an image is less than a defined width, it adds a class a certain element. This, for me, seems pretty easy but for some reason it's not working.
$(document).ready(function() {
var image = $('.work-each img');
if (image.width() < 500) {
$('.work-text').addClass('work-text-small');
}
});
This, should, add a class 'work-text-small' to the element 'work-text' if the image found under each .work-each is less than 500px.
Example of HTML (for each)
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
Thanks,
R
Use load instead, when DOM is ready only img tag is defined but the image isn't loaded yet. Its size comes when it's fully loaded
$(window).load(function () {
var image = $('.work-each img');
if (image.width() < 500) {
$('.work-text').addClass('work-text-small');
}
});
However as #rdck pointed if there are more images with class=".work-each img" code won't work so in that case you go trough each image and apply the class
$(window).load(function () {
var image = $('.work-each img');
image.each(function () {
var that = $(this);
if (that.width() < 500) {
that.next('div.work-text').addClass('work-text-small');
}
})
});
If you get dimensions using server code and set class accordingly, there would be no need to wait for image to load and css would immediately take effect as soon as html exists

Getting the amount of images which are in a specific div

I'm trying to get the amount of images which are stored in the post-content container of each post.
The layout of a post looks like this:
<div class="post">
<div class="post-toolbar">
<div class="post-date">date</div>
<div class="signs">
<div class="hearts">♥</div>
<div><img src="logo.png"></div>
<div><img src="logo2.png"></div>
</div>
<div class="post-title">title</div>
</div>
<div class="post-content">
<img src="image.png">
<img src="image.png">
</div>
</div>
And a Javascript snippet which looks like this:
$('.hearts').live("click",function() {
var amount = $(this).parent().parent().parent().find("img").size();
console.log(amount);
});
At the moment the value of amount is 4.
I'm sure the is a much nicer way to access the .post-content div with jQuery.
$('.hearts').live("click",function() {
var post = $(this).closest('.post'); // will find the first element with the class post up the DOM tree
var amount = $('.post-content img', post).size();
console.log(amount);
});
BTW you should really look into .delegate() and never use .live() again since live is way slower than delegate.
Or even better if you are on jQuery 1.7 or higher use .on().
How about $(this).parents(".post") ?
$('.hearts').live("click",function() {
var amount = $(this).parents(".post").children(".post-content").find("img").size();
alert(amount);
});

how can i move an element within a list of images? with JQuery

i have a list of images
<img src="image-1.jpg" />
<img src="image-2.jpg" />
<img src="image-3.jpg" />
<img src="image-4.jpg" />
<img src="image-5.jpg" />
whats the best way to reorder them such that image-1 is at the bottom? (but not necessarily image-1)
Edit: Preferably without using anything like the JQuery UI.
I would like this to be done with as little code as possible.
Simple and easy
$(function(){
var parent=$("img").parent();
$("img:first").appendTo(parent);
});
If you are not trying to create a dynamic sortable list and are just looking for a way to re-order images. You could try the following.
$("img[src$='image-1.jpg']").insertAfter("img[src$='image-5.jpg']");
This will allow you to find images and move them around based on the src of the image.
http://api.jquery.com/category/manipulation/
Look at the different methods that are available for DOMinsertion.
You can achieve this by using the jQuery UI:
http://jqueryui.com/demos/sortable/
(Supposing you want this to be dynamic, if not you should further explain the exact situation)
Then you want like something this? It sorts 1,2,3,4,5 to 5,4,3,2,1
<div id="reorder">
<img src="http://www.google.com.tr/images/srpr/logo3w.png" />
<img src="http://l.yimg.com/a/i/ww/met/logo/20100909/yahoo_logo_tr.png" />
<img src="http://www.rev2.org/wp-content/uploads/2009/06/bing-logo.png" />
<img src="http://a.l.yimg.com/a/i/us/sch/yhs4/altavista_logo.png" />
<img src="http://searchcdn.infospace.com/Dogpile-8.0.1.353/Content/Img/img_trans.gif?av=1353" />
</div>
<script>
$(function() {
$('#reorder').click(function() {
$("#reorder").randomize("img");
});
});
(function($) {
var onerandom = Math.random();
$.fn.randomize = function(childElem) {
return this.each(function() {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function() { return (Math.round(onerandom)-0.5); });
$this.remove(childElem);
for(var i=0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery);
</script>

Categories

Resources