Eventhandlers in a separate document - javascript

I'd like to keep all my JavaScripts in a separate document and I like it that way. Now I've had problems with the last bit of code to move from my HTML-code into my separate JavaScript document.
I got two eventhandlers that looked like this:
<a href="http://www.commercial.se" onclick="confirmLeave()" target="_blank">
and
<IMG SRC="folder/pic_small.jpg" alt="Description" onClick="view(this);">
This is the javascript code for the two eventhandlers:
function confirmLeave()
{
if(confirm("Vill du lämna Blomstermåla-Bladet?")) {
return true;
} else {
if(window.event) {
window.event.returnValue = false;
} else {
e.preventDefault();
}
return false;
}
}
And
function view(img) {
imgsrc = img.src.split("_")[0] + "_big.jpg";
viewwin = window.open(imgsrc,'viewwin', "width=790,height=444,location=0");
viewwin.focus();
}
I've managed to solve my problem of not having the javascript code in my HTML document for the first onClick eventhandler by changing my HTML to this:
<a href="http://www.commercial.com" id="external-link" target="_blank">
And adding this to my javascript document:
function init()
{
var link = document.getElementById("external-link");
link.onclick = confirmLeave;
}
window.onload = init;
I've tried adding a similar solution to the other eventhandler but I can't figure out the code I need to use for it to work. I would like to know how to add that event handler into the init function as well.

Try this
<a href="http://www.commercial.com" class="external-link" target="_blank">
<IMG SRC="folder/pic_small.jpg" alt="Description" id = "external-image">
function init() {
var link = document.getElementById("external-link");
var links = document.getElementsByClassName("external-link");
for (var i = 0; i < links.length; i++) {
links[i].onclick = confirmLeave;
}
var image = document.getElementById("external-image");
image.onclick = view;
}
window.onload = init;​
Instead of img in your function just use this
function view() {
imgsrc = this.src.split("_")[0] + "_big.jpg";
viewwin = window.open(imgsrc,'viewwin', "width=790,height=444,location=0");
viewwin.focus();
}

If you don't want to change the view function, you can do something similar, with the slight difference that you need to pass the image as an argument to the view function. You can do this by setting an anonymous function as the click handler.
<IMG SRC="folder/pic_small.jpg" alt="Description" id="some-img">
function init()
{
var img = document.getElementById("some-img");
img.onclick = function(){
view(this);
};
}

Related

How to combine two init function?

I've been working on speeding up my page loading speed. I have these two defers script to minimize loading time and improve performance.
The problem is only the last function will work. ex. if 'imgDefer' is in the last, only image will load on the front page. The same as 'vidDefer' if in last, only video will load and the image will not
I don't know how to combine these two init(). I'm not good at javascript.
These are the codes: (I place these codes in footer area)
video
<iframe src="" frameborder="0" allowfullscreen="allowfullscreen" data-src="https://www.youtube.com/embed/xxxxxx"></iframe>
image
<img class="img-responsive" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="imagesrource" alt="">
Video script
function init() {
var vidDefer = document.getElementsByTagName("iframe");
for (var s = 0; s < vidDefer.length; s++) {
if(vidDefer[s].getAttribute('data-src')) {
vidDefer[s].setAttribute('src',vidDefer[s].getAttribute('data-src'));
}
}
}
window.onload = init;
Image Script
function init() {
var imgDefer = document.getElementsByClassName("img-responsive");
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
So basically what it sounds like is that you'd like to be able to run multiple functions when the window.onload event gets triggered.
You could create two separate functions, like so:
function runVideoScript() {
var vidDefer = document.getElementsByTagName('iframe')
// ...
}
function runImageScript() {
var imgDefer = document.getElementsByClassName('img-responsive')
// ...
}
Then you can create an init function. This way, both functions will be called from the init function, and init will be called when window.onload gets triggered:
function init() {
runVideoScript()
runImageScript()
}
window.onload = init
In your current setup, the reason why only the last function gets called is because you're replacing window.onload with another function, and basically disregarding the first function.
Just make one init function which will be for example initVideo function and after it's executed run initImage.
function initVideo() {
var vidDefer = document.getElementsByTagName("iframe");
for (var s = 0; s < vidDefer.length; s++) {
if(vidDefer[s].getAttribute('data-src')) {
vidDefer[s].setAttribute('src',vidDefer[s].getAttribute('data-src'));
}
}
initImage();
}
function initImage() {
var imgDefer = document.getElementsByClassName("img-responsive");
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = initVideo();

addEventListener null, onclick works (onload did not work and js is in separate document)

I can use onClick in my HTML file to call upon functions created in my JavaScript file, however, attempting to use addEventListener does not work and I am not sure why. Error in console.log says that the addEventListner is null.
I am attempting to change the display of my web page via a click event.
I understand that addEventListener does not cancel out the previous event called, but even the first event called in my code does not trigger the change which is confusing.
After looking this up I tried the following:
Using window.onload = function(){} and placing the below code within the function.
document.getElementById('begin_game').addEventListener('click', beginGame);
document.getElementById('select_category').addEventListener('click', selectCategory);
Using this code independent of the window.onload function but the addEventListener still returned as null.
The beginGame and selectCategory functions reference the following code in the js file:
function Hide(x) {
const hidden = document.getElementsByClassName(x);
for (var i=0, length= hidden.length; i < length; i++) {
if ( hidden[i].style.display != 'none') {
hidden[i].style.display = 'none';
}
}
}
function Display(x) {
const show = document.getElementsByClassName(x);
for (var i = 0, length = show.length; i < length; i++) {
if (show[i].style.display != 'flex') {
show[i].style.display = 'flex';
}
}
}
//Below is how the functions are referenced
function beginGame() {
document.getElementById('welcome').style.display = 'flex';
Hide('start');
}
function selectCategory () {
Hide('welcome-content');
Display('category');
}
// Where I would place the event listeners I mentioned above
// document.getElementById('begin_game').addEventListener('click', beginGame);
// document.getElementById('select_category').addEventListener('click', selectCategory);
// When I used the window.onload function, I placed it at the bottom of the js page
Buttons from HTML file
<button type='submit' class='welcome-content' id='select_category'>
Categories
</button>
</div>
<h1 class= 'start'>
Math Maniacs
</h1>
<button type='submit' class='start' id='begin_button'>
START
</button>
Using window.onload was the correct solution, I realized that I was not enveloping all of the relevant js code with the onload function.
Before I did this
window.onload = function() {
document.getElementById('begin_game').addEventListener('click', beginGame);
document.getElementById('select_category').addEventListener('click', selectCategory);
}
However, I believe that didn't work because I did not place the functions the event listeners were referencing into the window.onload function.
Once I wrote the below
window.onload = function() {
function beginGame() {
document.getElementById('welcome').style.display = 'flex';
Hide('start');
}
document.getElementById('begin_button').addEventListener('click', beginGame);
function selectCategory() = {
Hide('welcome-content');
Display('category');
}
document.getElementById('select_category').addEventListener('click', selectCategory);
}
The code worked as intended

Handling missing images without jQuery

I would like to create a clean solution for handling missing image on the client
using <img src="image.gif" onerror="handleErrors()">
so far the handleErrors looks like this:
function handleErrors() {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
But I feel this is not scalable enough and the no image is also not accessible for screen readers.
What could be a more scalable and accessible solution for this problem?
Try using the alt text attribute for your images.
They are more accessible for screen readers.
Also you can create a module which on error hides the images and
replaces them with their alt text
Here is a module I wrote for handling such issues:
function missingImagesHandler() {
var self = this;
// get all images on the page
self.pageImages = document.querySelectorAll("img");
self.ImageErrorHandler = function (event) {
// hide them
event.target.style.display = 'none';
// replace them with alt text
self.replaceAltTextWithImage(event.target);
}
self.replaceAltTextWithImage = function (imageElement) {
var altText = imageElement.getAttribute("alt");
if (altText) {
var missingLabel = document.createElement("P");
var textnode = document.createTextNode(altText);
missingLabel.appendChild(textnode)
imageElement.parentNode.insertBefore(missingLabel, imageElement);
} else {
console.error(imageElement, "is missing alt text");
}
}
self.attachErrorHandler = function () {
self.pageImages.forEach(function (img) {
img.addEventListener("error", self.ImageErrorHandler);
});
}
self.init = function () {
// NodeList doesn't have forEach by default
NodeList.prototype.forEach = Array.prototype.forEach;
self.attachErrorHandler();
}
return {
init: self.init
}
}
var ImgHandler = new missingImagesHandler();
ImgHandler.init();
HTML:
<img id="myImg" src="image.gif">
JavaScript:
document.getElementById("myImg").onerror = handleErrors();
function handleErrors() {
document.getElementById("myImg").src = "http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png";
return true;
}
Give an ID to image and use this for call your function:
document.getElementById("myImg").onerror = handleErrors();
Giving an ID is more suitable way.

div with an id wont accept any event handlers JavaScript. No Jquery

Im trying to pause a timed slideshow when you're hovering over a div
<div id="play_slide" onMouseOver="clearTimeout(playTime)"></div>
If i put onMouseOver="clearTimeout(playTime)" inside an li on the page, it'll pause, so I know my code is correct, it just wont work on the div! Also if i get rid of the id, it will alert when i put an alert function into an event handler
This is the js.
var playTime;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
you can see this here: www.nicktaylordesigns.com/work.html
I would do it like this:
( and no inline script... just <div id="play_slide">Something</div> )
var playTime;
var indexPlay = 0;
var slideElement;
window.onload = function () {
slideElement = document.getElementById("play_slide");
slideElement.addEventListener('mouseenter', function () {
console.log('stop');
clearTimeout(playTime);
});
slideElement.addEventListener('mouseleave', function () {
console.log('continue');
playTime = setTimeout(playSlide, 2500);
});
playSlide();
}
function playSlide() {
var slideshow = slideElement.style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if (indexPlay > images.length - 1) {
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/" + images[indexPlay] + ".png')";
playTime = setTimeout(playSlide, 2500);
}
Fiddle
This issue is related to the script loading. Your script gets loaded after the DOM is processed so function doesn't get attached to the event.
If you are using jQuery then you can use below code.
$(function () {
$("#play_slide").mouseover(function(){
var playTime = 33;
clearTimeout(playTime);
});
});
If you don't want to use JQuery then you can do the same thing in JavaScript as below.
window.onload = function(){
document.getElementById("play_slide").onmouseover = function(){
var playTime = 33;
clearTimeout(playTime);
};
}
I got it! the div tag was somehow broken, I coded a div around it and gave it the event handlers and a class. That worked, then i simply changed the class to an id and got rid of the original div. Idk what was going on but it works now. Thanks for your suggestions!
Can you try this,
<div id="play_slide" onmouseover="StopSlide();">Stop</div>
<script>
var playTime;
var indexPlay;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
function StopSlide(){
window.clearTimeout(playTime);
}
playSlide();
</script>

Detecting Href Is Clicked

I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)
function checkLeave() {
var p = document.getElementByElementById('yeah');
if (p.href.onclick) {
//do something
}
else {
//do something else
}
}
window.onbeforeunload = checkLeave;
HTML CODE
//The goSomewhere goes to another page
<a id="yeah" href="javascript:goSomewhere();">
<img src="smiley.png">
</a>
Thanks in advance,
J
What you need to do is bind an event handler to each on the page.
This can be done with the following:
// Select all links
//var allLinks = document.querySelectorAll('a[href]');
var allLinks = document.links;
// Bind the event handler to each link individually
for (var i = 0, n = allLinks.length; i < n; i++) {
//allLinks[i].addEventListener('click', function (event) {});
allLinks[i].onclick = function () {
// Do something
};
}
You are testing for the presence of the onclick property to the <a> tag. It isn't present in the markup. Rather than using the onclick, the markup calls a script as the element's href. So you need to look for a script in the href instead:
var p = document.getElementByElementById('yeah');
if (p.href.indexOf("javascript") === 0) {
//do something
}
else {
// do something else
}
Maybe something like this? (just the idea)
document.getElementById('yeah').onclick = function() {
clicked = this.href;
};

Categories

Resources