script won't load with infinite scroll and masonry - javascript

I am using this script to get random background colors on my posts. It works fine when you load the page but when the new posts load the script doesn't work.
This is the code I used for the random background colors:
$(document).ready(function() {
$('.entry').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});
This is the infinite scroll / masonry code:
$(window).load(function () {
var $content = $('#posts');
$content.masonry({itemSelector: '.entry'}),
$content.infinitescroll({
navSelector : 'div#pagination',
nextSelector : 'div#pagination a#nextpage',
itemSelector : '.entry',
loading: {
finishedMsg: '',
img: 'http://static.tumblr.com/vk03xn8/Grsnluvip/ajax-loader.gif'
},
bufferPx : 600,
debug : false,
},
function( newElements ) {
var $newElems = $( newElements );
$newElems.hide();
$newElems.imagesLoaded(function(){
$content.masonry( 'appended', $newElems, true, function(){
$newElems.fadeIn(1300);
});
});
});
});
How can I combine both so that script works when new posts load?

Set your random color background logic in a function, call it on document ready and once new element are added. This could be for example:
function randColor() {
$('.entry:not(.randomized)').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).addClass('randomized').css("background-color", hue);
});
}
// doc ready
$(randColor);
And in appended callback:
$content.masonry( 'appended', $newElems, true, function(){randColor(); $newElems.fadeIn(1300);} );

Related

JQuery background URL uncaught syntax error

I'm trying to make a background slideshow using jQuery. I'm trying to have a hidden div (nextDiv) on the right of activeDiv slide nextDiv over activeDiv so that activeDiv will be overlapped by nextDiv. Once that is done, the background of nextDiv will then be changed to prepare for the new background image. Below is the code I have written.
// Scroll background
var bgClicked = false;
var bgList = [];
$(".bg-img").each(function(idx, el) {
bgList.push($(el).css('background-image').substr(4, 50));
bgList[idx] = bgList[idx].substr(0, bgList[idx].length -1);
});
var bgNum = bgList.length;
var bgNextDiv = $("#bg-next");
var bgActiveDiv = $("#bg-active");
var bgActive = 0;
var bgNext = 1;
// Scroll until clicked
console.log(bgList);
if(bgClicked == false) {
setInterval(function() {
$(bgList[bgNext]).animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});
}, 5000);
}
However, I'm getting
Uncaught Error: Syntax error, unrecognized expression: http://localhost:3000/img/bg2_2560x1440px.jpg`
when setting
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
I think I missed something, but I don't know where.
Please help?
Cheers,
Agi
EDIT 1
Content of bgList = ["http://localhost:3000/img/bg1_2560x1440px.jpg", "http://localhost:3000/img/bg2_2560x1440px.jpg"]
You are using bgList[bgNext] as jQuery selector that is why you are getting error.
So, use this instead:
$(".bg-img:eq(" + bgNext + ")").animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});

Jquery literally writes the word "false" when function returns no data

I have a jquery function to turn my links into google map links. My links are dynamic and pulled from db. So some of the links will be blank depending if that post has that data or not.
PROBLEM: If the post does not have data for that link (field), my function will litteraly write "False" on the front end instead of just being left blank (I want it to just be blank if there is no data.
I think it just needs to be made into an if / else statement but im not very good with jquery and need help
Here is the function: ( (retailers_init['full_address']) ) is the hook for the data)
$('address').each(function () {
var link = "<a href='http://maps.google.com/maps?q=" + encodeURIComponent(retailers_init['full_address']) + "' target='_blank'>" + (retailers_init['full_address']) + "</a>";
$(this).html(link);
});
And here is the larger function that this function (that changes (retailers_init['full_address']) to a google map link) resides in.
function init(retailer) {
var retailers_init = (typeof (retailer) != 'undefined') ? retailer : (typeof (retailers[0]) != 'undefined') ? retailers[0] : 'undefined';
if (typeof (retailers_init) !== 'undefined') {
var image = $('.storeinfo ._image');
var phone_number = $('.storeinfo ._phone_number');
var email = $('.storeinfo ._email');
var website = $('.storeinfo ._website');
var title = $('.storeinfo ._title');
var full_address = $('.storeinfo .full_address');
image.stop().animate({
'opacity': '0'
}, 100, function() {
image
.removeAttr('style')
.attr('src', image.attr('data-load'))
.addClass('loading')
.animate({
'opacity': '1'
}, 200);
});
$('<img/>').load(function() {
image.stop().animate({
'opacity': '0'
}, 200, function() {
image.removeClass('loading');
image.attr('src', retailers_init['image']);
setTimeout(function() {
image.css({'margin-top': '-' + (image.height() / 2) + 'px'});
image.animate({
'opacity': '1'
}, 200);
}, 100);
});
}).attr('src', retailers_init['image']);
title.html(retailers_init['title']);
full_address.html(retailers_init['full_address']);
phone_number.html(retailers_init['phone_number']);
email.attr('href', 'mailto:' + retailers_init['email']).html(retailers_init['email']);
website.attr('href', retailers_init['website']).html(retailers_init['website']);
$('address').each(function () {
var link = "<a href='http://maps.google.com/maps?q=" + encodeURIComponent(retailers_init['full_address']) + "' target='_blank'>" + (retailers_init['full_address']) + "</a>";
$(this).html(link);
});
}
}

How to replace a div content with other div using jquery or Javascript?

Hi all i am having some which i am appending to a div dynamically in my view....i have three ajax calls for different methods....firstly i show all the images of product in a div ....and if a user selects the price range the proucts will be displayed of that price range only and same for colours..what i want is i want this when user selects price range or color the div with all images should be replaced with the new images how can i do this can any one help me here
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductLayout", function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
scrollablediv();
});
});
function scrollablediv() {
$("div#makeMeScrollable").smoothDivScroll({
mousewheelScrolling: true,
manualContinuousScrolling: true,
visibleHotSpotBackgrounds: "always",
autoScrollingMode: "onstart"
});
}
</script>
<script type="text/javascript">
$(function () {
$("#slider-range").slider({
range: true,
min: 0,
max: 500,
values: [0,0],
slide: function (event, ui) {
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
},
change: function (event, ui) {
// when the user change the slider
},
stop: function (event, ui) {
// when the user stopped changing the slider
$.get("/api/ProductLayout", { firstPrice: ui.values[0], secondPrice: ui.values[1] }, function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
});
$("#amount").val("$" + $("#slider-range").slider("values", 0) +
" - $" + $("#slider-range").slider("values", 1));
});
</script>
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
</script>
and this is my html
<div id="makeMeScrollable" style="height: 400px; width: 400px;">
</div>
i should append all the images only to the above div replacing the previous images
As said by jaswant you can use .empty() method but not .empty().append() what this does is it will empty the data when ever an new record is binded so use .empty() method before your ajax call or json call
$("#makeMeScrollable").empty();
add the above line before your ajax call
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$("#makeMeScrollable").empty();
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
Try this,
$("#makeMeScrollable").html('ProdcutID<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' +
ele.Price + '</span><img src="' + ele.ImageURL + '" />');
You can always use html() in place of append() to remove the existing content.
or you can do empty the element before append with .empty().append()
EDIT (after comments)
var $div = $("#makeMeScrollable");
$div.empty();
$.each(data, function (idx, ele) {.append('ProdcutID' + '<span>' + ele.ProductID + '</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({
src: ele.ImageURL
}).appendTo("#makeMeScrollable");
});
You should do the empty as the first action in your success handler. Because the calls are asynchroneous, you will have the risk of products interfering with each other if you clear the area before you do the ajax call.
$(document).ready(function () {
$.getJSON("/api/ProductLayout").success(function (data) {
clearProductDisplayArea();
displayProductInfo(data);
scrollablediv();
});
});
function clearProductDisplayArea(){
$("#makeMeScrollable").empty();
}
function displayProductInfo(data){
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
}

creating jquery functions and using them for html elements?

im trying to create this function in javascript but its not working, im a bit new to js, so i don't what im really doing wrong here.
the code:
<div id="test">TESTING</div>
JS:
function animateDiv(div){
var text = $('#' + div + '"').text();
var doAnimate = function() {
$('span').each(function() {
var that = $(this);
setTimeout(function() {
that.animate({ fontSize: "90px" }, 1500 )
.animate({ fontSize: "50px" }, 1500 );
},that.index()*100);
});
}
$('#' + div + "'").html('');
for(i=0; i<text.length; i++) {
$('#' + div + "'").append('<span>'+text[i]+'</span>');
if(i==text.length-1) doAnimate();
}
}
// using the function here to run animation on div test from html
animateDiv(test);
the jsfiddle is here: http://jsfiddle.net/aA8Un/3/
This works now
function animateDiv(div){
var text = $('#' + div.id).text();
var doAnimate = function() {
$('span').each(function() {
var that = $(this);
setTimeout(function() {
that.animate({ fontSize: "90px" }, 1500 )
.animate({ fontSize: "50px" }, 1500 );
},that.index()*100);
});
}
$('#' + div.id).html('');
for(i=0; i<text.length; i++) {
$('#' + div.id).append('<span>'+text[i]+'</span>');
if(i==text.length-1) doAnimate();
}
}
animateDiv(test);
Actually you were trying to concatenate a string and an object by this $("#"+div), which is wrong, you should do this $("#"+div.id) which is legal.
You have to call the function using single/double quotes like
animateDiv("test");
instead of
animateDiv(test);
And remove '"' from your code everywhere
So Make it $('#' + div + '"') to $('#' + div)
Working Demo
var text = $('#' + div + '"').text();
replace with
var text = $('#' + div).text();
animateDiv('test')
subsitute $('#' + div + '"') with $('#' + div)

Jquery question about attribute manipulation

I'm new to jQuery and I can't figure out a solution for my problem.
I'm using jQuery easytooltip on some SVG objects in my website. Everything is working fine but I need to change some attributes of the tooltip on runtime. My document.ready function is like this:
$(document).ready(function () {
$("polygon").easyTooltip({
tooltipId: "easyTooltip2",
content: 'hello'
});
});
I want to be able,( on mouseover on my polygons) to read out attributes from my polygons and pass them into the content attribute, which is showed when the tooltip is showing... How can I access the content value to change it on runtime?
my plugin code now looks like this:
(function ($) {
$.fn.content = function (_content) {
$(this).easyToolTip({ content: _content })
};
$.fn.easyTooltip = function (options) {
// default configuration properties
var defaults = {
xOffset: 10,
yOffset: 25,
tooltipId: "easyTooltip",
clickRemove: false,
content: "",
useElement: ""
};
var options = $.extend(defaults, options);
var content;
this.each(function () {
var title = $(this).attr("title");
$(this).hover(function (e) {
content = (options.content != "") ? options.content : title;
content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
$(this).attr("title", "");
if (content != "" && content != undefined) {
$("body").append("<div id='" + options.tooltipId + "'>" + content + "</div>");
$("#" + options.tooltipId)
.css("position", "absolute")
.css("top", (e.pageY - options.yOffset) + "px")
.css("left", (e.pageX + options.xOffset) + "px")
.css("display", "none")
.fadeIn("slow")
}
},
function () {
$("#" + options.tooltipId).remove();
$(this).attr("title", title);
});
$(this).mousemove(function (e) {
$("#" + options.tooltipId)
.css("top", (e.pageY - options.yOffset) + "px")
.css("left", (e.pageX + options.xOffset) + "px")
});
if (options.clickRemove) {
$(this).mousedown(function (e) {
$("#" + options.tooltipId).remove();
$(this).attr("title", title);
});
}
});
};
})(jQuery);
You could do:
$("polygon").mouseover(function() {
$("polygon").easyTooltip({
tooltipId: "easyTooltip2",
content: 'changedContent'
});
});
this would recreate the tooltip: a better option would be to modify only the content, i'll look into the api to see if it's possible. (it's not possible to do with the api provided by the plugin i think, re-create the tooltip)
Check out .live():
$("polygon").live("mouseover", function() {
$("polygon").easyTooltip({
tooltipId: "easyTooltip2",
content: 'hello'
});
});
More info.

Categories

Resources