How to add alternating classes to dynamic feed of thumbnail images? - javascript

I am bringing a feed of a youtube user's video channel onto a page via two plugins called jYoutube and jGFeed.
jGFeed: http://archive.plugins.jquery.com/project/jgfeed
jYoutube: http://archive.plugins.jquery.com/project/jyoutube
I am getting stuck on why this isn't working... I thought it would be as easy as a simple if/else statement, but it is not working.
jQuery(document).ready(function($) {
$.jGFeed('http://gdata.youtube.com/feeds/base/users/POTATOwillEATyou/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile',
function(feeds){
// Check for errors
if(!feeds){
// there was an error
return false;
}
var html = '';
// do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
//My attempt at alternating classes:
if((i%2) == 0)
{
console.log('hello')
$(".thethumb").addClass("even");
}
else
{
console.log('NOPE')
$(".thethumb").addClass("odd");
}
//End of my attempt
html += '<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>';
}
$('#you_tube_feed').html(html);
}, 25);
});

Your issue is that you are are changing the class of ALL .thethumb, and they don't exist at the time you're running that code (they're inside your html string)
for(var i=0; i<feeds.entries.length; i++)
{
var entry = feeds.entries[i];
var $new = $('<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>');
if((i%2) == 0)
{
$new.addClass("even");
}
else
{
$new.addClass("odd");
}
$('#you_tube_feed').append($new);
}

Since you are using JQuery, it's even more simple . . . add all of the thumbnails first and then go back use the :even and :odd selectors to add the classes all at once:
$('.thethumb:even').addClass('odd');
$('.thethumb:odd').addClass('even');
You'll noticed that the classes are switched in comparison to the selectors . . . that is because the JQuery selector is 0-based, so items "0", "2", "4", etc. are actually the 1st, 2rd, 5th, etc. items in the selection.

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Missing closing tag from first item inserted into HTML page with jQuery

The first item in my list group has it's '< /a>' removed upon insertion into the page and my question is why and how do I fix this? If I console the html generated before and after the insertion the missing tag is there.
Here is the generator code:
function ObjMatched(item1, item2) {
this.item1 = item1;
this.item2 = item2;
}
var obj_list = '<div class="list-group>';
for (var i = 0; i < Obj.length;i++) {
if (Obj[i].item1 == selection) {
ObjMatched.item1 = Obj[i].item1;
ObjMatched.item2 = Obj[i].item2;
obj_list += '<a href="#" class="list-group-item" data-item1="' + ObjMatched.item1 + '" data-item2="' + ObjMatched.item2 + '" >' + ObjMatched.item1 + ', ' + ObjMatched.item2 + '</a>';
}
}
obj_list += '</div>';
$("#obj_block").append(obj_list);
Here is the HTML output:
<div id="obj_block">
<div class="list_group">
<a href="#" class="list-group-item" data-item1="mary" data-item2="smith">mary, smith
tom, jones
dirty, harry
</div>
</div>
As a consequence the first item does not appear as part of the list within the web browser and is not clickable. I have tried replacing append() with html() to no avail.
I have tested this in Chrome, Safari and Firefox all with the same result.
What am I doing wrong?
You're not closing the quotes on your first div:
var obj_list = '<div class="list-group>';
Change it to:
var obj_list = '<div class="list-group">';
And it will work. It's happening because the first apostrophe is closing this div and making the anchor tag invalid.

Iterate over specific CSS-id's with jQuery

I'm making an image gallery in which I want the user to be able to click on a thumbnail and get a bigger image displayed.
This is the php-code to iterate over all images in a directory on the server and display them and give them each a unique id.
echo '<div id="image' . $i . '" class="image">' . $thumbsrc . '</div>';
echo '<div id="bigimage' . $i . '" class="bigimage">' . $imagesrc . '</div>';
This works fine, I use
$(".bigimage").hide();
to hide the bigger images.
So what I could do now is this:
$("#image1").click(function() {
$("#bigimage1").show();
});
$("#bigimage1").click(function() {
$("#bigimage1").hide();
});
But I find for up to 30 pictures I can't write 30 instances of this so I wanted to loop it.
I tried
for (var i = 1; i < 30; i++) {
$('#image' + i).click(function() {
$('#bigimage' + i).show();
});
$('#bigimage' + i).click(function() {
$('#bigimage' + i).hide();
});
}
Which doesn't seem to work? Why not?
If I do
for (var i = 1; i < 10; i++) {
$('#image' + i).append('<p>test' + i + '</p>');
}
it appends paragraph's to every #image-element so looping selector's seem to work.
How would I do this?
Thanks beforehand.
That's because all of your click handlers use the same value, for understanding what happens, you can refer to this question: Javascript infamous Loop issue?
Since your elements have classes, you can use you classes instead. index method returns the index of the passed element in a collection. After getting the index, for selecting the corresponding element in another collection you can use the eq method.
var $img = $('.image');
var $bigImg = $('.bigimage').hide();
$img.on('click', function() {
var i = $img.index(this);
$bigImg.eq(i).show();
});
$bigImg.on('click', function() {
// this keyword refers to the clicked element
$(this).hide();
});

Add class to image onload - determine if landscape

I am trying to add a class to an image after determining if it is landscape or portrait. The problem I am having is that the class is being added to the img tag like this img.landscape which is obviously not registering properly. How can I properly achieve this: <img class="landscape" ?
$(data.images).each(function(j, imageURL){
var thumbnail = new Image();
thumbnail.src = imageURL;
thumbnail.onload = function() {
$('.images').append('<div class="image_mask"><img src="' + imageURL + '"/></div>');
if (thumbnail.width > thumbnail.height){
$(this).addClass('landscape');
}
};
});
My previous solution was to include an if/else statement with the class added in the appended string, but I am wondering if there is a cleaner way of approaching this. Thanks!
EDIT--
http://jsfiddle.net/curly33/XeHzK/1/
I'm assuming you want to add a class to the <img> tag you're dynamically creating a few lines before? If so, you can do so like this:
$('.image_mask img').addClass('landscape');
Since it's in a loop and you'll have multiple div.image_mask, use the array index j as a class qualifier:
$(data.images).each(function(j, imageURL){
...
thumbnail.onload = function() {
$('.images').append('<div class="image_mask image_mask' + j + '"><img src="' + imageURL + '"/></div>');
// ^^^^^^
if (thumbnail.width > thumbnail.height){
$('.image_mask' + j + ' img').addClass('landscape');
// ^^^^^^
}
};
});
UPDATE
Even though this was accepted, it feels clumsy to me to add class names like I originally suggested. A cleaner approach would be to use the j array index variable in combination with jQuery's eq function to locate the relevant image mask:
$('.images .image_mask').eq(j).addClass('landscape');
..then do away with the whole adding of classes approach.
Just put it in your string building
$(data.images).each(function(j, imageURL){
var thumbnail = new Image();
thumbnail.src = imageURL;
thumbnail.onload = function() {
var orientationClass = thumbnail.width > thumbnail.height ? "landscape" : "portrait";
$('.images')
.append(
'<div class="image_mask"><a href="' +
imageURL +
'"><img class="' +
orientationClass +
'" src="' +
imageURL +
'"/></a></div>'
);
};
});
Edit: More options
If you want to make it more verbose, but cleaner, you could build out the elements one by one:
var $img = $('<img />', {
class: thumbnail.width > thumbnail.height ? "landscape" : "portrait",
src: imageUrl
});
var $a = $('<a />', {
href: imageUrl,
}).append($img);
var $div = $('<div />', {
class: "image_mask"
}).append($a);
$('.images').append($div);
Or if you want to use the more efficient string building, but what it to be more readable/performant, you could do an array with a join:
var contents = [
'<div class="image_mask"><a href="',
imageURL ,
'"><img class="',
orientationClass,
'" src="',
imageURL,
'"/></a></div>'];
$('.images').append(contents.join(''));

HTML & JQuery: how to add array to displayBox

I am creating an IPad application using JavaScript and Html. Html for the page design and JavaScript for the functionality. I have a displayBox created using Html and I want to populate this with an array of countries using javascript.
It is currently adding just the first item in the array to the displayBox but the following error is appearing when i debug the application using firefox
EDIT:
I got it working, i had to take off the end of it
BEFORE:
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>').selectmenu('refresh');
AFTER
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>');
the .selectmenu('refresh') was causing the error
I have made some updates like adding $(document).ready() handler etc.
var arrayOfCountries = [{"name":"USA","id":1,"active":"Y"},{"name":"CANADA","id":2,"active":"Y"},{"name":"AALAND ISLANDS","id":270,"active":"Y"},{"name":"AFGHANISTAN","id":236,"active":"Y"},{"name":"ALBANIA","id":109,"active":"Y"},{"name":"ALGERIA","id":17,"active":"Y"},{"name":"AMERICAN SAMOA","id":307,"active":"Y"},{"name":"AMMAN","id":111,"active":"Y"},{"name":"ANDORRA","id":112,"active":"Y"},{"name":"ANGOLA","id":54,"active":"Y"},{"name":"ANGUILLA","id":22,"active":"Y"},{"name":"ANTARTICA","id":308,"active":"Y"},{"name":"ANTIGUA","id":113,"active":"Y"}];
$(document).ready(function(){
if ( $('#countrySelection').find('option').length == 0 ){
$.loadingMessage = "Retrieving Countries";
$.showPageLoadingMsg();
$.each(arrayOfCountries, function() {
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>');//.selectmenu('refresh');
});
$.mobile.hidePageLoadingMsg();
}
});​

Categories