Jquery Fast image switching - php

I have a php class that generates a map image depending on my db data. It is periodically updated thru a serInterval loop.
I am trying to update it with no flickering but I just can't. I've tried different methods (preloader, imageswitcher) with no success.
//first load
function map() {
$("#map").html("<img src=map.php?randval="+Math.random()+">");
}
//update it from setInterval calls
function updatemap() {
$("#map").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", "map.php?randval="+Math.random());
})
}
Is there any way to update the image with no flickering at all? I would prefer an inmediate swap insteado of a fade.
The problem I'm having is that after calling updatemap() the image just dissapears. ¿Maybe it is a problem with the attribute src I am parsing?
THanks for your help.

You may still get a very slight flicker.
function updatemap() {
var img = new Image();
img.onload = function(){
$("#map img").attr("src", img.src);
}
img.src = "map.php?randval="+Math.random();
}

You need to load the subsequent maps into a hidden element first. Then when they're loaded, swap them in.
<div id = "map"></div>
<img id = "load-map" src = "" alt = "" />
$(document).ready(function(){
$("#map").html("<img src=map.php?randval="+Math.random()+">");
setTimeout(loadImage,5000);
}
function loadImage()
{
$("#load-map")
.attr('src','map.php?randVal='+Math.random())
.load(function(){
$("#map img").src($("#load-map").src);
setTimeOut(loadImage,5000);
});
}

Related

Edit DIVs after .append()

My algorithm:
I get the DIV text from php/SQL ($.get( "read.php"...)
APPEND contenteditable div with loaded text by jQuery
check the div value, if there is errors in text I make div red (assign class, $(this).addClass("fill_red");)
on every change of text - check and assign/remove class if needed.
Problem is: with preloaded text - everything is working.
But when I append div using JS - check function don't works.
I searched the web, maybe on() method helps me.
But what event?
It should be something like onload, onchange..?
(yes, I could make div generated by php and solve the problem, but I dont want full refresh)
Thank you!
part of code:
//texts load
$(function() {
$.get( "read.php", function( data ) {
var ionka = data.split(' ');
ionka.forEach(function(item, i, arr) {
var app_text = "<div id=\"segm" + i + "\" contenteditable role=\"textbox\">" + item + "</div>";
$("#textarea").append(app_text);
});
});
//checks
var intRegex = new RegExp('^[0-9/\]{5}$');
$('#textarea div').each(function(i,elem) {
if(!intRegex.test($(this).text())) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
});
// edit on change. Blur because of contenteditable
var segm_array = [];
$('#textarea div').each(function(i,elem) {
$(this).blur(function() {
if (segm_array[i]!=$(this).text()){
segm_array[i] = $(this).text();
if(!intRegex.test(segm_array[i])) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
}
});
});
You dont show much code here, but my guess is that you are trying to add class before new data is loaded into dom
$.get( "read.php" ).done(function( data ) {
// addClass etc
});

Change Image jQuery

I am not new to jQuery, however this should work and isnt:
html:
<a href='<?=$s['url'];?>' class='playbutton'><img src='http://i.domain.net/icons/play.png' width=20></a>
jquery $("a.playbutton").click():
$(this).find("img").attr("src","http://i.domain.net/icons/stop.png");
If I change the attr to addClass("jimbo") I get the class jimbo added to my image. So it is finding the img tag fine, but not changing the source. Can someone tell me why?
full jquery function is:
$("a.playbutton").click(function(e) {
var current = $("#jplayer").data().jPlayer.status.src
var playing = current.split("/");
var href = encodeURIComponent($(this).attr("href"));
if(playing[3] != href) {
$("#jplayer").jPlayer("setMedia", {mp3: "http://mp3.domain.net/" + href});
$("#jplayer").jPlayer("play");
$(this).find("img").attr("src","http://i.domain.net/icons/stop.png");
$("a.playbutton > img").each(function () {
$(this).attr("src","http://i.domain.net/icons/play.png");
});
} else {
$("#jplayer").jPlayer("stop");
$("#jplayer").jPlayer("clearMedia");
}
return false;
});
All works fine apart from $(this).find("img").attr.. line. Like i said, If i change attr to addClass, it adds the class fine. Meaning that it can find the correct <img> tag okay.
(URLs have been changed to domain.net)
use prop in place of attr
$(this).find("img").prop("src","url");
Maybe you've forgot to add the return false to the callback, check this out:
http://jsfiddle.net/YnT5L/1/
$("a.playbutton").click(function() {
$(this).find("img").attr("src","http://i.domain.net/icons/stop.png");
return false;
});

Jquery replaceWith:replace one php file with another php file based on screen resolution

I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.

how to remember scroll position of page

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);

What comparable Javascript function can reference a file like PHP's include()?

What is the best way to reference or include a file using Javascript, looking for the closest functionality of PHP's include() ability.
I would check out Javascript equivalent for PHP's include:
This article is part of the 'Porting
PHP to Javascript' Project, which aims
to decrease the gap between developing
for PHP & Javascript.
There is no direct equivalent - you can either go with the function I linked above or use document.write to write out a new script tag with a src pointing to the file you wish to include.
Edit: Here is a rudimentary example of what I mean:
function include(path) {
document.write(
"<script type=\"text/javascript\" src=\"" + path + "\"></script>"
);
}
Edit 2: Ugh, what an ugly example - here is a better one:
function include(path) {
script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
if (head = document.getElementsByTagName("head")[0]) {
head.appendChild(script);
}
}
document.write is a hackish way of doing things and I shouldn't have recommended it. If you go with one of my examples please use the second one.
I have a script that I wrote a while back (using Mootools) that allows for one to include javascript files on the fly (with a callback function after its loaded). You can modify it to work the library of your choice if you choose.
Note the gvi prefix is just my namespace and that gvi.scripts is an array containing all the javascript files currently included on the page, those can be removed if you want. Also, the filename function can be removed, that was just added to make my life easier [require('some-script') vs require('js/some-script.js')].
//if dom isn't loaded, add the function to the domready queue, otherwise call it immediately
gvi.smartcall = function(fn) {
return (Browser.loaded) ? fn() : window.addEvent('domready', fn);
}
//For dynamic javascript loading
gvi.require = function(files, callback, fullpath) {
callback = callback || $empty;
fullpath = fullpath || false;
var filename = function(file) {
if (fullpath == true) return file;
file = ( file.match( /^js\/./ ) ) ? file : "js/"+file;
return ( file.match( /\.js$/ ) ? file : file+".js" );
}
var exists = function(src) {
return gvi.scripts.contains(src);
}
if ($type(files) == "string") {
var src = filename(files);
if (exists(src)) {
gvi.smartcall(callback);
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
gvi.smartcall(callback);
}
});
}
} else {
var total = files.length, loaded = 0;
files.each(function(file) {
var src = filename(file);
if (exists(src) && loaded == total) {
gvi.smartcall(callback);
} else if (exists(src)) {
loaded++;
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
loaded++;
if (loaded == total) gvi.smartcall(callback);
}
});
}
});
}
}
And you call it like
gvi.require('my-file', function() {
doStuff();
});
//or
gvi.require(['file1', 'file2'], function() {
doStuff();
});
jQuery has a plugin for this: http://plugins.jquery.com/project/include
Instead of using javascript and making our work more complex, we have pretty easy way to include external file using the IFRAME tag in HTML.
**
<iframe src="....../path/filename.html" width="" height="">
**
We can also control iframe using CSS if even more customization required .

Categories