How to reload offsite image sources every 30 seconds with JavaScript? - javascript

I have some images from another source that need to refresh from their offsite source every 30 seconds. I would like to use JavaScript to accomplish this so as to avoid an entire page reload.
Presently I've attempted something similar to this question: "reloading a page after every 10 sec in rails 3.1"
(This is a Rails application, but I probably don't need a Rails specific answer in this case.)
Notwithstanding, I am ending up with no appreciable result when I add a div around the link + image nor when I add a div to the image itself. I have attempted both solutions in this example by creating a element-reload.js.
The first solution that's marked as the answer simply reloads the page with nearly all of the page elements absent. The second solution makes the image that I'm trying to refresh actually disappear upon first refresh when I surround the link + image with a div, but when I place the id upon which it's acting on the actual image tag, it yields nothing.
I'm sure I'm missing something rather simple since JS is not a strong suit for me at the moment.
Finally, I do have a number of sources to refresh and would like to see an example of performing this for a class vs an id if possible, but having more granular control over each one may be best in the end for varied times for the refreshes.

If you're up for jQuery, this can be done quite easily:
$(function() {
setInterval(function() {
$('img').each(function() {
$this = $(this);
$this.attr('src', $this.getAttribute('src') + '?timestamp=' + new Date().getTime());
console.log($this.prop('src'));
});
}, 30 * 1000);
});
In order to prevent browser caching, you have to fool the browser and load the image with a GET request variable timestamp. It doesn't matter what the parameter is, but the image will load brand-new and not from cache because the URL changes.
jQuery is famous for its use of CSS-like selectors.
Replace $('img') with one of these:
$('img.yourClassName'); // Class
$('#your_id, #another_id, ...'); // ID(s). Omit the comma for a single id
$('img[id^="common_base_id"]'); // Selects all images with an id that starts with "common_base_id".
There's also the :not() selector, which can filter your results:
$('img.yourClassName:not(.do-not-reload)');
$('img.yourClassName:not([src="img/spinner-skip.gif"])');

Related

Automate page turning with jFlip

I want to have a page turn effect like the one seen on this page: jFlip demo except I want to automate the page turning, like make it happen every second, 20 times (or however many images I have). I want to be able to trigger this animation to run either on page load, when a button is clicked, etc.
Unfortunately I don't understand jQuery all that well and the plugin's events seem rather complicated to me, probably mostly due to my inexperience with jQuery. Any help on which direction I should go, methods I should try? I am not limiting myself to jQuery or even Javascript, this is just the example I have found that achieves my desired effect.
You can find the updated code here. replace this with old one.
Usage :
var jFlip = new Flip("#g1",300,300,{background:"green",cornersTop:true,scale:"fit"});
// here #g1 is a jquery selector (make sure it returns only one).
// The structure is Flip(JQselector,width,height,options)
then use the jFlip object to flip slides/pages
jFlip.flipMe() // for next slide
jFlip.flipMe(true) // for prev slide
for binding a function to slide change event you can use
$("#g1").bind("flip.jflip",function(event,index,total){
$("#l1").html("Image "+(index+1)+" of "+total);
});
// here the selector is same as the one passed inside jFlip function.
Try this and let me know the feedback.

Place one image from JavascriptObject to multiple places

Situation: I have a tiny http server that can only handle 4 connections at any given time. When opening a web page, my web browser sends a get request for every image resource asynchronously (tries to open more than 4 connections at the same time). This causes some bad behaviour.
Initial solution: I wrote a JS function that loads the images sequentially and stores them in a dictionary
var loadedImages = {};
like so:
var img = new Image();
img.src = <img_location>;
loadedImages[<img_name>] = img;
After all the images are loaded i try to place them in various places in the DOM. The important part is that i need to place the same picture in multiple places. I do it like this:
//For all the elements that need to have the same image DO:
var img = loadedImages["<img_name>"];
$(this).html(img);
Problem: What happens is that as soon as the code puts the image in the SECOND element, the image gets removed from the FIRST element. When the image gets put in the THIRD element, it gets removed from the SECOND element. So what happens is that basically only the last element contains the image, while all the others are empty.
Question: How can I place the same image from my javascript dictionary (or any other javascript object) on multiple DOM elements?
Edit:When using something like
//For all the elements that need to have the same image DO:
var img = loadedImages["<img_name>"];
$(this).html($(img).clone());
as proposed by Tamil Vendhan and Atif Mohammed Ameenuddin, the image gets placed on all the elements and that is ok, but the browser requests the image from the server every time it comes to that line of code. So it is not really a good solution. Same goes when i use "cloneNode()"
Try using the clone method in jQuery
$(this).html($(img).clone());
Use jQuery.clone:
$(this).html($(img).clone());
Update:
Yes, browser will make the request. But it will use the cached image if it is already loaded.
Check your debugger's net panel to confirm this. You will see (from cache) under Size column.

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

Best way to rearrange positioning of images/divs with javascript/jquery?

I took a peek at the source of http://wonderwall.msn.com and noticed how all the span tags that the blocks of the wall have don't seem to be associated with any ID. It makes me very curious how they are able to accomplish the animated repositioning of elements when you click on one of the blocks/images without associated ID.
I am curious how you can click on say an image and get other images around it to move to the side. Is it some sort of formula or algoirthm?
I would like to accomplish getting say, 5 spans/blocks, clicking on one, and getting others to animate/move to the sides.
IDs are not necessary and often harmful. You don't need them, generated or otherwise.
When you put an element on a page with an ID, you're making the claim that there should be only one of whatever it is. Seldom is this true. More often, what you want to do is associate some behavior with some of the elements on the page, of which there may be many, one or zero.
In this case, there are lots of little image dealies, which when clicked, rearrange themselves. I don't have an algorithm for you for calculating how they should move, but here's a framework for how you could achieve the same with jQuery.
// create jQuery plugin for highlighting and shuffling brick dealies
(function($){
function expandify() {
var href = this.attr('href');
// create a popup containing the href
return this;
}
function shuffle() {
this.each(function(index, elem){
// calculate new position and move the element there.
});
return this;
}
$.fn.expandify = expandify;
$.fn.shuffle = shuffle;
})(jQuery);
// attaches behaviors to elements on the page after they've loaded
// either $.ready, or window onload, or after some ajaxing takes place
$('.wallBrick')
.click(function(e){
$(e.target)
.expandify();
$('.wallBrick')
.not(e.target)
.shuffle();
});
The IDs are generated via JavaScript on-the-fly. You won't see it in the source, but you'll see it if you inspect it with Firebug.

Inserting smilies into div with jQuery

I'm working on some small chat application. I want to implement smilies over there so when i click on some smiley it will appear in textarea where user enters his message and when user clicks on select i want smilies to appear in div that contains the conversation.
After some workarounds i got to idea that replacing textarea with div contenteditable="true"
doesn't work that well so i did wrap certain smiley name with ':' like :wink: in textarea but still i need to replace :wink: with real span containing image as background.
Problem is i don't see a way to make this dynamically but doing each one by one.
for example:
if ($('.line:contains(":wink:")').length > 0) {
var oldLineHTML = $('.line:contains(":wink:")').html();
$('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));
I have plenty of smilies so doing this very resource expensive function will costs me much and also will cause me lots of problems during maintenance.
How can i do that dynamically? Or maybe you have better solution which will require to re-design... I'm up to it if it is required.
thanks
}
var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));
My suggestion is read every string that is wrapped by colons :[something]:, then convert it into span. So that you don't have to define every smile, and it is easy to maintain.
If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:
function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
//Replace the wink here
});
}
$(document).ready(function(){
replaceWinks();
});
I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.
Jeaffrey Gilbert's idea is good, but I have another one that may be interesting:
write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:
using these smilies:
1- [smile]
2- [wink]
3- [shy]
will lead to the following markup
1- <div class="smile"></div>
2- <div class="wink"></div>
3- <div class="shy"></div>
and using CSS, you will give every class of them, a different background image, which is the smile image.
by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself

Categories

Resources