JavaScript append gone crazy - javascript

I am trying to build a simple 3 grid gallery, the images inside it are all with different heights and I was after a tiled gallery... So I have made one that works with a bit of JavaScript.
However, when I tried to add another gallery in the same page, something weird happened, live preview here: http://loai.directory/test/gallery
The HTML, CSS and JS can be found fully placed in this jsfiddle: http://jsfiddle.net/aY5Gu
As you can see in the live preview, all the gridElemetns in grid3 are appending to grid3 in all the threeGrid galleries! After trying to debug, I have concluded that the problem is from the JS:
//Three Grids System
var gridElement = $(".gridElement", ".grid3");
GalleryGrid(); $(window).resize(GalleryGrid);
function GalleryGrid() {
var grid3 = $('.threeGrids .grid3');
var width = $(window).width();
if (width < 1024 && width > 770) {
var grid1 = $('.threeGrids .grid1');
var grid2 = $('.threeGrids .grid2');
for (var i = 0; i < gridElement.length; i++) {
if (i < gridElement.length / 2) {
grid1.append(gridElement[i]);
} else {
grid2.append(gridElement[i]);
}
}
} else {
grid3.append(gridElement);
}
}
What is going wrong? I can't seem to be able to go figure out what is wrong from there.

That's because .threeGrids and .grid1... appear more than one time on your page. Therefore jquery automatically appends things to all of them.
Try selecting by something like:
$('.wrapper').each(
function(){
var grids = $(this).find('.threeGrids');
(...do manipulation with grids...)
}
);
This way you enter each .wrapper separately and deal with only elements that are inside it.

Related

Assigning string to div value from javascript function across pages

I have a web app that outputs the results of a function as a double. The function compares two text documents and returns the percentage indicating the percentage of similarity between the two documents. When the user clicks a Compare button, the function runs and takes the user from the compare.jsp page to the results.jsp page, and displays a loading-bar that is filled in like so:
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}"
data-stroke="">
</div>
This works fine, the fan bar gets the correct percentage. However, I am also trying to color the fan bar using the data-stroke value based on this percentage. I have a simple javascript function to do this, but can't figure out how to pass the value. I've tried running the function in the body tag of the results.jsp page using "onload", but this doesn't work. Here is my JavaScript function:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.getElementById("levenshtein-distance");
if (percent <= 40.00) {
elem.setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem.setAttribute("data-stroke", orange);
} else {
elem.setAttribute("data-stroke", red);
}
}
I've done quite a bit of searching and can't seem to find an example that helped me solve this. Any help is very much appreciated.
////Update:
Trinh, that worked to change the color, thanks! My problem now is that I do, in fact, have multiple 'levenshtein-distance' ids and I am looping through them. So currently everything is being set to the same color. I should have mentioned this initially, sorry. I am comparing multiple pairs of files and outputting the loading-bar for each pair. If you have some idea about how to resolve the looping issue, that would be great, but thanks for the original solution either way! I updated my javascript function as follows:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.querySelectorAll("[id^=levenshtein-distance]");
for (var i in elem) {
if (percent <= 40.00) {
elem[i].setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem[i].setAttribute("data-stroke", orange);
} else {
elem[i].setAttribute("data-stroke", red);
}
}
}
And the full bit of code with the html loop is, and I am now calling the barSetLD(percent) at the very bottom of the page as you suggested:
<c:forEach items="${studentResults}" var="result" varStatus="loop">
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}">
</div>
</c:forEach>
<script type="text/javascript">
barSetLD("${result.percentage}");
</script>
Put your code at the very bottom of the page where all DOM has been loaded. Or at least make sure <div id="levenshtein-distance"/> exist and fully loaded before calling this document.getElementById("levenshtein-distance");. Also double check if you have multiple levenshtein-distance id...

Reload a content almost invisibly and no blinking effect using JAVASCRIPT

I'm writing a small progam wherein I'm getting data using $.get then display the data so far so good and then there's this part then when I click a certain link it refresh the page but it has this blinking effect. Is there a way on how to reload the content get the new updated content then replace the previously loaded data.
NOTE: I didn't use setInterval or setTimeout function because it slows down the process of my website. any answer that does not include those functions are really appreciated.
Here's the code
function EmployeeIssues(){
$('#initial_left').css({'display' : 'none'});
var table = $('#table_er');
$.get('admin/emp_with_issues', function(result){
var record = $.parseJSON(result);
var data = record.data,
employees = data.employees,
pages = data.pages;
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
}else{
$('#er_tab_label').html('<b>No employees with issues yet.</b>');
}
});
table.html('');
}
then this part calls the function and display another updated content
$('#refresh_btn').on('click', function(e){
e.preventDefault();
var tab = $('#tab').val();
if(tab == 'er'){
EmployeeIssues();
}
});
What should I do to display the content without any blinking effect?
thanks :-)
This section might be the issue :
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
} else ...
It seems you're asking table_er to fade in once per run of the loop whereas s there can only be one such table, you only need to do it once ?
first try re-arringing it like this:
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
table.append(write_link(employees[i])); // function that displays the data
}
$('#table_er').fadeIn('slow'); // only do this after the table has all its html
if(pages){
$('#pagination').html(pages);
}
} else ....
Another possibility is that you're running through a loop and asking jquery to do stuff while the loop is running. It might be better to work out the whole HTML for the new page data in a string and then get the screen to render it in one line. I cna't do this for you as I don't know what's in write_link etc but something like this ..
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
var sHTML ="";
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
sHTML+=write_link(employees[i]); // maybe this is right ? if write_link returns an HTML string ?
}
table.append(sHTML); // add the HTML from the string in one go - stops the page rendering while the code is running
$('#table_er').fadeIn('slow'); // now show the table.
if(pages){
$('#pagination').html(pages);
}
} else ...

Placing elements within a container div into an array - jQuery or JavaScript

I have a div that contains a number of Instagram images, produced by the instafeed.js plugin. After running the plugin, the resultant HTML looks like this:
<div id="instafeed">
<a><img /></a>
<a><img /></a>
<a><img /></a>
etc...
</div>
I am trying to find a way to load the contents of this div into an array; I believe that the easiest way would be to just take the tags, which is fine.
I'm pretty inexperienced with both JS and jQuery, which is why I'm having difficulty achieving this and I've not been able to find any forum posts that quite do what I'm hoping to achieve.
So far, all I'm trying to do is load the contents of the div into an array and print it back out to the document, which should (in my mind anyway) add the tags back into the HTML. I'm trying with both JavaScript and jQuery and having little success with either. I'd appreciate any thoughts:
JS:
var containerDiv = document.getElementById('instafeed');
var pics = containerDiv.getElementsByTagName('img');
console.log(pics); //Tells me at least that I have an array of img
for (var i = 0; i < pics.length; i++) {
document.write(pics[i]);
} //Seemingly does nothing
jQuery:
(I'm really sorry if this code is just all wrong, I really don't know jQuery very well at all)
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
console.log(pics[i]);
}
});
Any thoughts, tips or pointers would be much appreciated.
Edit:
Just to add a little background to my problem, to avoid causing any more confusion.
I'm trying to pull four random images from a user-specific Instagram feed for display on a website. instafeed.js can pull just four images and it can randomise the images, but Instagram itself always sends the four most recent images, so the plugin is just randomising the order of the same four pictures each time.
I'm trying to let the plugin send through every picture, which will go into the div instafeed. From here I want to load all of the contained images into an array so that I can randomly pick four images for display on the site.
JQuery code that you write is correct. Only you need the div where you need to put the images.
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
$('div#yourDiv').append(pics[i]);
}
});
See the line of the for()
You can extract only the SRC of the images and then make like you want
$('#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
console.log(pics); // returns an array of src.
Thank you to everyone who has tried to help me along with this. It turns out that the problem I was having stemmed from my query attempting to run before instafeed.js had been able to pull the images through from Instagram, and so there was nothing for it to find in the div. I've managed to fix this with a setTimeout.
For anyone who is interested, and just in case anyone else might come across this in future with a similar problem, here is my complete code (it's a little inelegant I'm sure, but I'm still a relative novice at JS.)
function snagImages() {
var pics = [];
$('div#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
reduceGallery(4, pics);
}
function reduceGallery(limit, pics) {
if (limit === undefined) {
limit = 4;
}
var gallery = [];
while (gallery.length < limit) {
var j = Math.floor(Math.random() * pics.length);
if ( gallery.indexOf(pics[j]) > -1) {
continue;
}
gallery.push(pics[j]);
}
displayPics(gallery);
}
function displayPics(gallery) {
for (var i = 0; i < gallery.length; i++) {
document.getElementById('gallery').innerHTML += '' + '<img src="' + gallery[i] + '" alt="Gallery Image" />' + '';
}
}
var userFeed = new Instafeed( {
options
});
userFeed.run();
setTimeout(function() { snagImages() }, 500);

Javascript is not running

This javascript code is supposed to switch when clicked an image to images from a folder within the html file folder.
After it gets to the last image, if you click again it resets to the first image.
Also there's a fade in and out effect on the appearing images.
It doesn't work and I suspect I wrote the path files to the images wrong somehow and the .attr doesn't change the src of the first image to the others.
Things to keep in mind = an extremely beginner programmer, just picked up html and css in about 2 days, I would appreciate any kind of help!
This is the code:
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum])";
//$(indexNum).css("height=600px,width=1000px")
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
)};
)};
)};
You got a couple of errors in your code,
You swapped the closing ")" and "}" in the last two lines and you have a random " in the code.
Here's a working example:
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
indexNum = (indexNum + 1) % imageName.length; // this will count 0,1,2,0,1,2,0,1,2... always looping through your images
$(this).fadeOut(function() { //in this context, this refers to the #head, reading it from the DOM over and over again isn't efficient
$(this).attr("src", imageName[indexNum]);
}).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="head1" src="http://placehold.it/200x200" alt="">
Just a small note: Your script (and mine) don't take into account loading times, this means that it will probably work fine on your computer, locally, but once you put it on a server, you will see the image fadeout, then fadein and still be the same image and then swap to the new image all of a sudden. This happens because it has some loading time. If you want to fix this you'll need some other events. Or you could load all images into the page and then just swap the one that is currently shown.
Even thought this has been answered, here is a fiddle with your original code corrected. http://jsfiddle.net/goqz3coj/
Its better to see how your code should work instead of been giving a different code
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
});
});
});
SECOND VERSION Waits for image load before showing again...
http://jsfiddle.net/goqz3coj/2/
By simply using .load you can wait for the image to load and then show.
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$( "#head1" ).load(function() {
$("#head1").fadeIn(500);
// Handler for .load() called.
});
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
});
});
});
Jonas Grumann took your image urls as easier to show with actual images.

Loop through all images and change size?

The script below works for posts that are already on the page. But, when I click on load more posts, the new posts that get added to the page don't change the source of the image so that they are blurry.
Is there a way to loop through all images and change the src of it, even the ones that are not shown?
function resizeThumb(size) {
var popularPost = document.getElementById('Blog1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s72\-c/g, "\/s" + size + "-c");
image[i].width = size;
image[i].height = size;
}
}
// Resize to 200 × 200
resizeThumb(200);
Yes. Basically locate the button that loads more, find it's name.
If your button looks like this:
Load more
Put this before it so it looks like this:
<span onclick="resizeThumb(200); ">
Load more
</span>
It's the lousiest solution but the question is lousy too.

Categories

Resources