I'm trying to implement a simple image slider on my website but it doesn't seem to want to work. Nothing happens at all. Nothing I can think of has worked thus far so I thought I'd ask here. This is my code.
window.onload = function(){
image = document.getElementById("slideShow");
index = 0;
setInterval(slide, 3000);
};
function slide(){
index++;
if(index >= 6) {index = 0;}
path = "images/Slideshow/image"+index+".jpeg";
image.setAttribute("src",path);
}
window.onload is pretty cheesy because nobody seems to agree on what onload actually means.
i would recommend you use
document.addEventListener("DOMContentLoaded", function(){
// code
});
Another thing u should be aware of is slow loading. If the scripts gets loaded after the ready event has been fired then your code will never trigger.
A solution is wrapping the ready function is a seperate module.
var eventReady;
(function(){
var funcArr = [];
eventReady = function(func){
funcArr.push(func);
}
document.addEventListener("DOMContentLoaded", function(){
for(var i=0;i<funcArr.length;i++){
try{
funcArr[i]();
}
catch(e){
throw(e);
}
finally{
continue;
}
};
eventReady = function(func){
func();
}
});
})();
and then use the module like:
eventReady(function(){
// code
})
Related
Having issue with - what I supposed to be - basics scope fundamentals.
I am using Javascript with Require JS structure, here are where the issue occurs:
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append(//Some HTML);
}
GameManager.prototype.showGame = function() {
//Code
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
$("#game").removeClass("display-none");
}
I am using this.body succefully so I want to use the same way for this.game but it doesnt work. I can manage to make it work by using directly $("#game") but it's making jquery running through the DOM everytime so not really optimized...
I certainly am missing some basics points here, can someone explain ?
Thanks
This is working for me. I can remove display-none class from div without a problem. It wont display however. You need to change css. this.body.css("display","block"); for example.
window.onload = function() {
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append();
}
GameManager.prototype.showGame = function() {
//Code
this.body.css("display", "block");
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
//$("#game").removeClass("display-none");
}
var myGame = new GameManager();
myGame.showGame();
}
Forgive my naivety, this probably is quite obvious, I just can't see it now.
Please tell me what is wrong with the following code:
$('#iframe1').load(function(){
$('#iframe2').load(function(){
alert('loaded!');
});
});
The idea is to wait until both iframes have fully loaded, then alert "loaded" - of course this is a simplified example for the sake of stack.
The script sits in script tags at the end of the body of the html doc.
#Quertiy answer is perfectly fine, but not very jQuery-ish. It is hard-coded for 2 iframes only.
The beauty of jQuery is that you can make it work for the most number of people, with as little friction as possible.
I've advised a very simplistic plugin that does nearly what is present on that answer, but in a more open way. It not only works on iframes, but also on images, audio, video and whatever has a onload event!
Without further due, here's the code:
(function($){
$.fn.extend({allLoaded: function(fn){
if(!(fn instanceof Function))
{
throw new TypeError('fn must be a function');
}
var $elems = this;
var waiting = this.length;
var handler = function(){
--waiting;
if(!waiting)
{
setTimeout(fn.bind(window), 4);
}
};
return $elems.one('load.allLoaded', handler);
}});
})(window.jQuery);
It works by adding a load handler to every element in that selection. Since it is a plugin, you can use in whatever way you decide to use it.
Here's an example, that loads 30 random images:
//plugin code
(function($){
$.fn.extend({allLoaded: function(fn){
if(!(fn instanceof Function))
{
throw new TypeError('fn must be a function');
}
var $elems = this;
var waiting = this.length;
var handler = function(){
--waiting;
if(!waiting)
{
setTimeout(fn.bind(window), 4);
}
};
return $elems.one('load.allLoaded', handler);
}});
})(window.jQuery);
$(function(){
//generates the code for the 30 images
for(var i = 0, html = ''; i < 30; i++)
html += '<img data-src="http://lorempixel.com/g/400/200/?_=' + Math.random() + '">';
//stuffs the code into the body
$('#imgs').html(html);
//we select all images now
$('img')
.allLoaded(function(){
//runs when done
alert('loaded all')
})
.each(function(){
//the image URL is on a `data` attribute, to delay the loading
this.src = this.getAttribute('data-src')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="imgs"></div>
Your problem, as said before many times, is that you have a load event attached to your iframe. That event is fired everytime the content change.
After that, you set a new event on #iframe2. When it's content changes, it will fire events left and right, above and beyound what you wish!
The best aproach is to keep track of which ones you loaded or not. After all have been loaded, you simply run the function.
The problem is that you're waiting until #iframe1 loads before you attach a handler for #iframe2 loading. So if #iframe2 loads first, you'll never get your callback.
Instead, watch the load event on both of them and track which ones you've seen:
var seen1 = false,
seen2 = false;
$('#iframe1, #iframe2').load(function(){
if (this.id == "iframe1") {
seen1 = true;
} else {
seen2 = true;
}
if (seen1 && seen2) {
alert('loaded!');
}
});
Why do you expect 2nd iframe to load after the first one?
~function () {
var loaded = 0;
$('#iframe1, #iframe2').load(function (){
if (++loaded === 2) {
alert('loaded!');
}
});
}()
I'm trying to up my js foo and start to use the module patter more but I'm struggling.
I have a main page with a jquery-ui element that pops up a dialog that loads an ajax requested page for data entry. The below code is contained within the popup ajax page.
After the pop up is loaded the Chrome console is able to see and execute ProtoSCRD.testing() just fine. If I try to run that in the jQuery.ready block on the page, I get:
Uncaught ReferenceError: ProtoSCRD is not defined
Yet i can execute toggleTypeVisable() in the ready block and life is good. Can anyone shed some light?
$(document).ready(function() {
setHoodStyleState();
$('#hood-style').change(function(){
hstyle = $('#hood-style').val();
if ( hstyle.indexOf('Custom') != -1) {
alert('Custom hood style requires an upload drawing for clarity.');
}
setHoodStyleState();
});
setCapsState();
$('#caps').change(function(){
setCapsState();
});
setCustomReturnVisibility();
$('#return').change(function(){ setCustomReturnVisibility(); });
toggleTypeVisable();
$('#rd_type').change(function(){
toggleTypeVisable();
});
ProtoSCRD.testing();
});
function toggleTypeVisable(){
if ( $('#rd_type').val() == 'Bracket' ) {
$('.endcap-ctl').hide();
$('.bracket-ctl').show();
}
if ( $('#rd_type').val() == 'Endcap' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').show();
}
if ( $('#rd_type').val() == 'Select One' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').hide();
}
}
ProtoSCRD = (function($, w, undefined) {
testing = function(){
alert('testing');
return '';
}
getDom = function(){
return $('#prd-order-lines-cnt');
}
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
calling the popup dialog like so - which is in fact in another ready in a diff file on the parent page:
// enable prototype button
$( "#proto-btn" ).click(function(e){
e.preventDefault();
showPrototype();
});
I don't know if it will solve your problems at all, but you are definitely missing several var statements you really should have:
var ProtoSCRD = (function($, w, undefined) {
var testing = function(){
alert('testing');
return '';
};
var getDom = function(){
return $('#prd-order-lines-cnt');
};
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
IMHO, it's best practice to use var for every variable you declare. (Function declarations do so implicitly.)
But I really don't know if this will help solve anything. But it should store everything in its proper scope.
Update
Here's one possible issue: if the document is already ready (say this is loading at the end of the body), then perhaps jQuery is running this synchronously. Have you tried moving the definition of ProtoSCRD above the document.ready block?
The following code doesn't seem to work in IE (using 9) - Test 1 fires but test 2 does not. Is there a different way of doing this for IE?
<script>
$(document).ready(function () {
overlay = $("#overlay");
img = $("#myimg");
alert('test 1');
img.load(function () {
alert('test 2');
var myPercent = 50;
var myHeight = $("#myimg").height() / 100 * myPercent;
overlay.height(myHeight);
overlay.width($("#myimg").width());
$(".percent").css('margin-top', $("#myimg").height()/2 - $(".percent").height()/2);
$(".percent").text(myPercent + "%");
});
});
</script>
EDIT: Fixed it by using $(window).load(function() { instead of document ready and removing the function
From the jQuery API of .load()
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
shortcut is to execute a function when an image (or collection of
images) have completely loaded. There are several known caveats with
this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the
same src as before
It doesn't correctly bubble up the DOM tree Can cease to fire for
images that already live in the browser's cache
Make use of $(window).load():
$(window).load(function() {
alert('test 2');
var myPercent = 50;
var myHeight = $("#myimg").height() / 100 * myPercent;
overlay.height(myHeight);
overlay.width($("#myimg").width());
$(".percent").css('margin-top', $("#myimg").height()/2 - $(".percent").height()/2);
$(".percent").text(myPercent + "%");
});
Technically you should be able to add onload parameter on img tag which calls js function that does the same thing. I haven't tested this but it's worth a shot.
...
<script>
function resizeImg ($img) {
// code
}
</script>
...
<img onload="resizeImg($(this));" src="foo.png" />
You might as well use jQuery then.
...
<script>
$("#fooImg").load(function () {
// code
});
</script>
...
<img id="fooImg" src="foo.png" />
If you don't mind using a plugin, Paul Irish made a simple plugin to handle image loading, seeing as .load() does not handle images. The plugin was moved and turned into a project which can be found on GitHub.
$.fn.imagesLoaded = function (callback) {
var elems = this.filter('img'),
len = elems.length,
// data uri bypasses webkit log warning (thx doug jones (cjboco))
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
elems.bind('load', function () {
// check image src to prevent firing twice (thx doug jones (cjboco))
if (--len <= 0 && this.src !== blank) {
callback.call(elems, this);
}
}).each(function () {
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined) {
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
this.src = blank;
this.src = src;
}
});
};
You can see it in action at this fiddle.
http://jsfiddle.net/denniswaltermartinez/c4DMH/
img.load() as an event is not supported by IE. Actually it is not necessary, that $(document).ready() function has already ensure img and other elements loaded. Just remove it.
My javascript code stops when the side loads from the cache manifest in the Fullscreen WebApp Mode(iPad3/iOS6).
This has the consequence that you cant do anything in the first 5 seconds. After that you can use the site as normal.
1) Why does the JavaScript Code stop? (Event Problem?)
2) How can i fix it?
Involved is:
jquery-1.8.2.min.js
EDIT:
I have experimented and found out that the JavaScript code runs normally after the event onNoUpdate and onUpdateReady. Until these two events are initiated, it passes a large time. So this is not a option.
EDIT2:
`<script type="text/javascript">
$(document).bind('touchmove', false);
$(document).ready(function () {
applicationCache.onupdateready = function () {
if (confirm("Ihre Applikation wurde aktualisiert. Soll die Darstellung neu geladen werden?")) {
window.location.reload();
}
}
applicationCache.onnoupdate = function () {
}
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
if (a[i].className.match("noeffect")) {
// Here happens nothing
}
else {
a[i].onclick = function () {
load();
window.location = this.getAttribute("href");
return false;
};
}
}
}
);`
Try inserting some logs in key spots to find out exactly where in the code the pause happens. Usually when you narrow it down enough, the answer becomes clear.