JavaScript image at onload event - javascript

I am trying to load a new image every time the previously loaded image has finished loading.
The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.
The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.
function registerEventHandler(node, event, handler) {
if (typeof node.addEventListener == "function")
node.addEventListener(event, handler, false);
else
node.attachEvent("on" + event, handler);
}
// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
node.removeEventListener(event, handler, false);
else
node.detachEvent("on" + event, handler);
}
function load_next_photo() {
var loading_list = create_photo_list();
alert(loading_list.length);
if (loading_list.length > 0) {
img[loading_list[0]]['loaded'] = 1;
registerEventHandler($("load_img"), "onload", load_next_photo());
$("load_img").src = img[loading_list[0]]['img'];
}
else {
alert("nothing");
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}

Can't get my head around what you currently have, but such code works just fine:
var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;
window.onload = function() {
LoadImage();
};
function LoadImage() {
//stop condition:
if (_index >= _images.length)
return false;
var url = _images[_index];
var img = new Image();
img.src = url;
img.onload = function() {
_index++;
LoadImage();
};
document.getElementById("Container").appendChild(img);
}
This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/
This is plain JS, feel free to ask about any part for elaboration. :)

Related

removeEventListener from body not working

I'm trying to remove an event listener after a function has been called. But the event listener for "keyup" stays attached to the body, no matter what I try. What is wrong with the code?
function displayImage() {
//this is a simplified version of the code
var outerFrame = document.createElement('div');
outerFrame.className = 'popup-outer';
document.body.appendChild(outerFrame);
document.body.addEventListener('keyup', hideImage.bind(outerFrame), false);
}
function hideImage(e) {
if (e.keyCode === 27) {
// this doesn't work, it stays attached to the body element
document.body.removeEventListener('keyup', hideImage, false);
document.body.removeChild(this);
}
e.preventDefault();
}
It's because technically
hideImage.bind(outerFrame)
is different from
hideImage
because the first one returns a copy of the function hideImage.
So when you try to unbind hideImage, the event manager does not find it because it registred a copy of it and thus nothing is removed :-/.
EDIT :
In your case, I guess you have no other choice but keeping track of your listeners. I went ahead and made this quickly, it should fix your problem.
var listeners = {};
function createDiv() {
var outerFrame = document.createElement('div');
outerFrame.className = 'popup-outer';
return outerFrame;
}
function displayImage() {
var div = createDiv();
bindEvent(div);
document.body.appendChild(div);
}
function bindEvent(el) {
var handler = function(e) {
hideImg.call(el, e);
}
listeners[el] = handler;
document.body.addEventListener('keyup', handler, false);
}
function hideImg(e) {
if (e.keyCode === 27) {
// listeners[this] refers to the "private" handler variable we created in the bindEvent function
document.body.removeEventListener('keyup', listeners[this], false);
delete listeners[this];
document.body.removeChild(this);
}
}

How to trigger JavaScript custom events correctly

I am struggling to understand how a custom event type is linked to a specific user action/trigger. All documentation seems to dispatch the event without any user interaction.
In the following example I want the event to be dispatched once a user has been hovering on the element for 3 seconds.
var img = document.createElement('img');img.src = 'http://placehold.it/100x100';
document.body.appendChild(img)
var event = new CustomEvent("hoveredforthreeseconds");
img.addEventListener('hoveredforthreeseconds', function(e) { console.log(e.type)}, true);
var thetrigger = function (element, event) {
var timeout = null;
element.addEventListener('mouseover',function() {
timeout = setTimeout(element.dispatchEvent(event), 3000);
},true);
element.addEventListener('mouseout', function() {
clearTimeout(timeout);
},true);
};
I have a trigger but no logical way of connecting it to the event.
I was thinking about creating an object called CustomEventTrigger which is essentially CustomEvent but has a third parameter for the trigger and also creating a method called addCustomEventListener, which works the same as addEventListener but when initialised it then passes the target Element to the custom event trigger which then dispatches the event when it's instructed to.
Custom events have to be triggered programatically through dispatchEvent, they are not fired by the DOM. You will always need to explictly call them in your code, such as in response to a user-generated event such as onmouseover, or a change of state such as onload.
You're very close to a working implementation, however you're immediately invoking dispatchEvent in your setTimeout. If you save it into a closure (as below) you can invoke dispatchEvent while passing your element after setTimeout has finished the timeout.
It's also good practice to declare your variables at the top of a file, to avoid possible scope issues.
var img = document.createElement('img'), timeout, event, thetrigger;
img.src = 'http://placehold.it/100x100';
document.body.appendChild(img);
img.addEventListener("hoveredForThreeSeconds", afterHover, false);
thetrigger = function (element, event) {
timeout = null;
element.addEventListener('mouseover',function() {
timeout = setTimeout(function(){ element.dispatchEvent(event) }, 3000);
},true);
element.addEventListener('mouseout', function() {
clearTimeout(timeout);
},true);
};
function afterHover(e) {
console.log("Event is called: " + e.type);
}
event = new CustomEvent("hoveredForThreeSeconds");
thetrigger(img, event);
I have created a method called addCustomEventListener, which works the same as addEventListener but when initialised passes the target Element to the custom event trigger which dispatches the event when it says, so in this case it only dispatches if the timeout reaches 3 seconds.
var img = document.getElementById('img');
window.mouseover3000 = new CustomEvent('mouseover3000', {
detail: {
trigger: function(element, type) {
timeout = null;
element.addEventListener('mouseover', function() {
timeout = setTimeout(function() {
element.dispatchEvent(window[type])
}, 3000);
}, false);
element.addEventListener('mouseout', function() {
clearTimeout(timeout);
}, false)
}
}
});
window.tripleclick = new CustomEvent('tripleclick', {
detail: {
trigger: function(element, type) {
element.addEventListener('click', function(e) {
if(e.detail ===3){
element.dispatchEvent(window[type])
}
}, false);
}
}
});
EventTarget.prototype.addCustomEventListener = function(type, listener, useCapture, wantsUntrusted) {
this.addEventListener(type, listener, useCapture, wantsUntrusted);
window[type].detail.trigger(this, type);
}
var eventTypeImage = function(e) {
this.src = "http://placehold.it/200x200?text=" + e.type;
}
img.addEventListener('mouseout', eventTypeImage, false);
img.addEventListener('mouseover', eventTypeImage, false);
img.addCustomEventListener('mouseover3000', eventTypeImage, false);
img.addCustomEventListener('tripleclick', eventTypeImage, false);
<img id="img" src="http://placehold.it/200x200?text=No+hover" ;/>
I think this could be useful to others so please feel free to improve on this.

jQuery change button image not working

Just learning jQuery and am using it to change the background image on a button triggered by a mouseover event. All of the console output fires at the correct times, but my image never changes. No errors are thrown. What am I doing wrong?
In the <head> element, I have this preloading script:
function preloader() {
if (document.images) {
console.log("preloading images");
contact_green = new Image();
contact_green.src = "http://www.xxxx.com/images/contact_green.png";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
That seems to work fine, in the sense that I get the output "preloading images". Not sure that it has the correct scope, however.
Then, in the <body> element, I have this button defined:
<td>
<button id='contact' class='CXIII' onclick="btnContact()">
<img id="logo" src="images/contact_blue.png">
</button>
</td>
Finally, I have a script that is supposed to change the image on this button upon a mouseover event:
<script>
function showHover(img) {
console.log("show hover");
if (img) img.src = contact_green;;
}
$("#contact").hover(
function () {
console.log("mouse in");
showHover(this);
},
function () {
console.log("mouse out");
}
);
</script>
I get the console output, but the image doesn't change. There are no errors thrown, either.
You are setting an object, not the source of the image
img.src = contact_green;;
needs to be
img.src = contact_green.src;
And you are not setting the image, but the button.
showHover(this);
needs to be
showHover($(this).find("img")[0]);
and since you are using jQuery
$(window).load(preloader);

Src for the images does not set properly

I have some divs that has a class named class='tweetCon'
each containing 1 image and I want to check if the image source exist or not so if it is available I dont do anything but if not I will change the image source with an appropriate image my code is as follow:
$('.tweetimgcon').children('img').each(function () {
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
$(this).attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
and also imageExists() is as follow:
function imageExists(url, callback,callback2) {
var img = new Image();
img.onload = function() { callback(true);callback2(); };
img.onerror = function() { callback(false);callback2(); };
img.src = url;
}
now the problem is that the src for the images that are not available does not set properly though when I check the src of those images by console.log it shows that they are properly set but it is not shown and when I use inspect element of chrome I can see that src is not set . Can anyone help me?
The point is $(this) doesn't point to your object, because you call $(this) inside your imgExists callback function but NOT the jQuery callback function each, so the this object doesn't point to your original img tag!
The solution should be save the object reference first, try the below:
$('.tweetimgcon').children('img').each(function () {
var _this = $(this);
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
_this.attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
Just for a little tip for a better callback function use call.
function imageExists(url, cb, ecb) {
var img = new Image();
img.onload = function() { cb.call(img,true,url); };
img.onerror = function() { ecb.call(img,false,url); };
img.src = url;
}
I added img as the first argument and that will then be your this keyword instead of window.
Testing Bin

AddEventListener function won't execute

The iFrameOn function runs on page load, and up until it is supposed to execute the iBold function is works fine. I've gone through and debugged as much as possible, and everything seems fine. When I output every variable to the console, the values are correct. It's just that one line (iBold(targetiFrame);) that won't run. I'm not sure what's going on.
function iFrameOn() {
var iFrames = document.querySelectorAll('form > iframe'); //Get all iframes in forms
var bolds = new Array(), italics = new Array(), underlines = new Array(), targetiFrame;
var getRT = document.getElementsByClassName('richText');
for (var rtIndex = 0; rtIndex < getRT.length;rtIndex++) { //Rich text event listeners
var rtid = getRT[rtIndex].id;
if (getRT[rtIndex].className == "richText bold") { //Bold text event listener
console.log('The id is: '+rtid);
bolds.push(rtid);
console.log('The bolds array contains: '+bolds);
} else if (getRT[rtIndex].className == 'richText underline') { //Underline text event listener
underlines.push(getRT[rtIndex]);
} else if (getRT[rtIndex].className == 'richText italic') { //Italic text event listener
italics.push(getRT[rtIndex]);
}
}
bolds.forEach(function(e, i, a) { //e = a[i]
console.log('e is '+e);
document.getElementById(e).addEventListener('click', function() {
console.log(e+' was clicked!');
targetiFrame = document.getElementById(e).getAttribute('data-pstid');
iBold(targetiFrame);
}, false);
});
}
function iBold(target) {
if (target == 0) {
document.getElementById('richTextField').contentDocument.execCommand('bold', false, null);
document.getElementById('richTextField').contentWindow.focus();
} else {
document.getElementById(target).contentDocument.execCommand('bold', false, null);
document.getElementById(target).contentWindow.focus();
}
}
I apparently had another iBold function in another js file

Categories

Resources