Chrome Extension : Tab issues - javascript

The code below attempts to open a new tab for the corresponding post object, when its image is clicked in popup.html. For some reason, the new tab is blank and isn't going to the right page as specified by this.Link in the Post singleton. Any help would be appreciated!
<html>
<head>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<script>
var req = new XMLHttpRequest();
req.open(
"GET",
"http://thekollection.com/feed/",
true);
req.onload = showPosts;
req.send(null);
function showPosts() {
var elements = req.responseXML.getElementsByTagName("item");
for (var i = 0, item; item = elements[i]; i++) {
var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;
var txtLink = link.toString();
var txtDesc = description.toString();
var start = txtDesc.indexOf("\"") + 1;
var end = txtDesc.indexOf(".jpg") + 4;
var imgURL = txtDesc.substring(start, end);
var post = new function(){
this.Link = txtLink;
this.Description = txtDesc;
this.ImageURL = imgURL;
this.imgElement = document.createElement("image");
this.displayTab = function(){
chrome.tabs.create({'url' : this.Link}, function(tab){});
}
}
post.imgElement.addEventListener("click", post.displayTab, false)
post.imgElement.src = post.ImageURL;
document.body.appendChild(post.imgElement);
}
}
</script>
</head>
<body>
</body>

You register post.displayTab as an event listener on post.imgElement which means that the value of this will be post.imgElement when the event listener is called. Consequently, there is no Link property (this.Link is undefined). One way to avoid this problem would be registering the event handler differently:
post.imgElement.addEventListener("click", function() {
post.displayTab();
}, false)
post.displayTab is called as a method of the post object here so this variable will be set correctly. The other option is to stop using this in post.displayTab:
this.imgElement = document.createElement("image");
var me = this;
this.displayTab = function(){
chrome.tabs.create({'url' : me.Link}, function(tab){});
}
The me variable remembers the "correct" this value.

Related

javascript audio gets lauder each click

I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;
var rotateImage = function() {
var i = 0;
var randomNumbers = createThreeRandomNumbers();
var interval = window.setInterval(function () {
i++;
document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;
if (i === items.images.length -1) {
i = -1;
}
}, 125);
var clearData = function () {
correctItem = "";
secondItem = "";
thirdItem = "";
selectedItems = "";
selectedItemsShuffled = "";
removeNodeChildren("button-1");
removeNodeChildren("button-2");
removeNodeChildren("button-3");
};
var removeNodeChildren = function (obj) {
var myNode = document.getElementById(obj);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
};
var resetGame = function () {
clearData();
document.getElementById("buttonWrapper").classList.remove("show");
rotateImage();
}
document.getElementById("imageToRotate").addEventListener("click", function (e) {
// select 3 items
correctItem = getSelectedItemDetails(e);
secondItem = getRandomItem(correctItem);
thirdItem = getSecondRandomItem(correctItem, secondItem);
selectedItems = [correctItem, secondItem, thirdItem];
selectedItemsShuffled = shuffleArray(selectedItems);
// create the numbers 1 to 3 randomly
var order = createThreeRandomNumbers();
// remove the rotating effect
clearInterval(interval);
// set the images to the buttons in a random order.
setItemsToButtons(order, selectedItemsShuffled);
//show the buttons
showButtons();
// Create an event which triggers when a button is clicked.
document.getElementById("buttonWrapper").addEventListener("click", function(e) {
var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
var clickedButton = e.srcElement.id;
if (valueOfButtonPressed === correctItem) {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-check green" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/correct.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
} else {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-times red" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/wrong.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
}
});
});
};
// 1: hide the buttons
hidebuttons();
// 2: Replace the title
replaceTitle("Animals");
// 3: set up image rotation until it's clicked.
rotateImage();
})();
Any help will be much appreciated. Cheers!
I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");
do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.

2 self-invoking javascript functions running

I have a container which contains a primary image and 2-3 thumbnails each. I wanted the user to be able to change the image by clicking on the thumbnail of its parent. Aside from that, I want the containers to be draggable/sortable so that users can be able to compare them easily.
This is why I made these 2 self invoking functions in my javascript file.
This one is to change the primary image into the image of the thumbnail.
$(document).ready(function(){
$('.thumb-img').on('click', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});
While this one is used to drag and drop the containers to interchange positions.
(function() {
"use strict";
var dragAndDropModule = function(draggableElements){
var elemYoureDragging = null
, dataString = 'text/html'
, elementDragged = null
, draggableElementArray = Array.prototype.slice.call(draggableElements) //Turn NodeList into array
, dragonDrop = {}; //Put all our methods in a lovely object
// Change the dataString type since IE doesn't support setData and getData correctly.
dragonDrop.changeDataStringForIe = (function () {
var userAgent = window.navigator.userAgent,
msie = userAgent.indexOf('MSIE '), //Detect IE
trident = userAgent.indexOf('Trident/'); //Detect IE 11
if (msie > 0 || trident > 0) {
dataString = 'Text';
return true;
} else {
return false;
}
})();
dragonDrop.bindDragAndDropAbilities = function(elem) {
elem.setAttribute('draggable', 'true');
elem.addEventListener('dragstart', dragonDrop.handleDragStartMove, false);
elem.addEventListener('dragenter', dragonDrop.handleDragEnter, false);
elem.addEventListener('dragover', dragonDrop.handleDragOver, false);
elem.addEventListener('dragleave', dragonDrop.handleDragLeave, false);
elem.addEventListener('drop', dragonDrop.handleDrop, false);
elem.addEventListener('dragend', dragonDrop.handleDragEnd, false);
};
dragonDrop.handleDragStartMove = function(e) {
var dragImg = document.createElement("img");
dragImg.src = "http://alexhays.com/i/long%20umbrella%20goerge%20bush.jpeg";
elementDragged = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(dataString, this.innerHTML);
//e.dataTransfer.setDragImage(dragImg, 20, 50); //idk about a drag image
};
dragonDrop.handleDragEnter = function(e) {
if(elementDragged !== this) {
this.style.border = "2px dashed #3a3a3a";
}
};
dragonDrop.handleDragOver = function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
dragonDrop.handleDragLeave = function(e) {
this.style.border = "2px solid transparent";
};
dragonDrop.handleDrop = function(e) {
if(elementDragged !== this) {
var data = e.dataTransfer.getData(dataString);
elementDragged.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData(dataString);
}
this.style.border = "2px solid transparent";
e.stopPropagation();
return false;
};
dragonDrop.handleDragEnd = function(e) {
this.style.border = "2px solid transparent";
};
// Actiavte Drag and Dropping on whatever element
draggableElementArray.forEach(dragonDrop.bindDragAndDropAbilities);
};
var allDraggableElements = document.querySelectorAll('.draggable-droppable');
dragAndDropModule(allDraggableElements);
})();
The two functions work but when I drag the container and change its position, the first function doesn't work anymore.
It's probably because you drag it and recreate the element node.
you can use Event to solve the problem.
$(document).ready(function(){
// It delegate thumb-img event to body, so whatever you recreate thumb-img,is all right
$('body').on('click', '.thumb-img', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});

Changes to Javascript created element doesn't reflect to DOM

I have a class, that is supposed to display grey overlay over page and display text and loading gif. Code looks like this:
function LoadingIcon(imgSrc) {
var elem_loader = document.createElement('div'),
elem_messageSpan = document.createElement('span'),
loaderVisible = false;
elem_loader.style.position = 'absolute';
elem_loader.style.left = '0';
elem_loader.style.top = '0';
elem_loader.style.width = '100%';
elem_loader.style.height = '100%';
elem_loader.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
elem_loader.style.textAlign = 'center';
elem_loader.appendChild(elem_messageSpan);
elem_loader.innerHTML += '<br><img src="' + imgSrc + '">';
elem_messageSpan.style.backgroundColor = '#f00';
this.start = function () {
document.body.appendChild(elem_loader);
loaderVisible = true;
};
this.stop = function() {
if (loaderVisible) {
document.body.removeChild(elem_loader);
loaderVisible = false;
}
};
this.setText = function(text) {
elem_messageSpan.innerHTML = text;
};
this.getElems = function() {
return [elem_loader, elem_messageSpan];
};
}
Problem is, when I use setText method, it sets innerHTML of elem_messageSpan, but it doesn't reflect to the span, that was appended to elem_loader. You can use getElems method to find out what both elements contains.
Where is the problem? Because I don't see single reason why this shouldn't work.
EDIT:
I call it like this:
var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
loader.stop();
document.getElementById('cover').style.display = 'block';
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();
xml.loadXML() is function that usually takes 3 - 8 seconds to execute (based on download speed of client), thats why I'm displaying loading icon.

Strange behaviour of included JS file in node.js

I am making a node app that is in it current state very simple, but I get an issue I can't figure out.
The generated html of my express app looks like this:
<html style="" class=" js no-touch svg inlinesvg svgclippaths no-ie8compat">
<head>
...
<script type="text/javascript" src="/javascripts/mouse.js"></script>
...
</head>
<body class="antialiased" style=""><div class="row"><div class="row">
<script>
var mouse;
var X = 0;
var Y = 0;
window.onload = function()
{
alert(Mouse());//=> undefined
mouse = Mouse();
mouse.setMouseMoveCallback(function(e){ //THIS LINE FAILS: "Cannot call method 'setMouseMoveCallback' of undefined"
X = e.x;
Y = e.y;
alert("move");
});
}
...
</html>
The include script tag in the header adds this javascript file:
function Mouse(onObject){
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
var mouseDownCallbacks = [0, 0, 0, 0, 0, 0, 0, 0, 0];
var mouseTracer = 0;
var tracePosArray;
var target = onObject;
if(!onObject){
onObject = document;
}
onObject.onmousedown = function(evt) {
mouseDown[evt.button] = 1;
mouseDownCount--;
if(mouseDownCallbacks[evt.button] != 0){
mouseDownCallbacks[evt.button](evt);
}
}
onObject.onmouseup = function(evt) {
mouseDown[evt.button] = 0;
mouseDownCount--;
}
var mousemoveCallback;
onObject.onmousemove = function(evt){
//Tracing mouse here:
if(mouseTracer){
tracePosArray.push([evt.pageX,evt.pageY]);
}
if(mousemoveCallback){
mousemoveCallback(evt);
}
}
var mouseWheelCallback;
onObject.onmousewheel = function(evt){
if(mouseWheelCallback){
mouseWheelCallback(evt);
}
}
var mouseOverCallback;
onObject.onmouseover = function(evt){
if(mouseOverCallback){
mouseOverCallback(evt);
}
}
var mouseOutCallback;
onObject.onmouseout = function(evt){
if(mouseOutCallback){
mouseOutCallback(evt);
}
}
//TODO: There is a bug when you move the mouse out while you are pressing a button. The key is still counted as "pressed" even though you release it outside of the intended area
//NOTE: might have fixed the bug. Do some further investigation by making a smaller element.
this.anyDown = function(){
if(mouseDownCount){
for(p in mouseDown){
if(mouseDown[p]){
return true;
}
}
}
}
this.setLeftDownCallbackFunction = function(fun){
mouseDownCallbacks[0] = fun;
}
this.setRightDownCallbackFunction = function(fun){
mouseDownCallbacks[2] = fun;
}
this.setMiddleDownCallbackFunction = function(fun){
mouseDownCallbacks[4] = fun;
}
this.setSpcifiedDownCallbackFunction = function(num, fun){
mouseDownCallbacks[num] = fun;
}
this.leftDown = function(){
if(mouseDownCount){
return mouseDown[0] != 0;
}
}
this.rightDown = function(){
if(mouseDownCount){
return mouseDown[2] != 0;
}
}
this.middleDown = function(){
if(mouseDownCount){
return mouseDown[4] != 0;
}
}
this.setMouseMoveCallback = function (callback){
mousemoveCallback = callback;
}
this.setMouseWheelCallback = function (callback){
mouseWheelCallback = callback;
}
this.setMouseOverCallback = function (callback){
mouseOverCallback = callback;
}
this.setMouseOutCallback = function (callback){
mouseOutCallback = callback;
}
this.enableTracer = function(){
tracePosArray = new Array();
mouseTracer = 1;
}
this.getMouseTracerData = function() {
return tracePosArray;
}
}
So: I have assured that the JS file is loaded. But none the less I am not able to access the Mouse() method in my window.onload function in the body, it shows up as undefined. This is very strange to me because if I create a HTML file that does exactly the same thing I am able to access it.
What is going on here? Is there some magic trickery in node.js / express that disables this kind of interaction?
Additional notes:
I am using Jade as the template engine.
The "mouse.js" file works. I have used it several times before.
I am using socket.io for communication between the client and server.
Complete header:
<head><title>My awesome title</title><link rel="stylesheet" href="/stylesheets/foundation.min.css"><link rel="stylesheet" href="/stylesheets/normalize.css"><link rel="stylesheet" href="/stylesheets/style.css"><script type="text/javascript" src="/socket.io/socket.io.js"></script><style type="text/css"></style><script type="text/javascript" src="/javascripts/jquery.min.js"></script><script type="text/javascript" src="/javascripts/vendor/custom.modernizr.js"></script><script type="text/javascript" src="/javascripts/vendor/zepto.js"></script><script type="text/javascript" src="/javascripts/mouse.js"></script><meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"><meta name="viewport" content="width=device-width"></head>
That would throw an error if the Mouse function is undefined. The reason alert shows 'undefined' is that the Mouse function doesn't return anything, hence undefined. It should be used as a constructor, as in 'new Mouse()'

Undefined error using javascript objects

I am newbie to javascript objects and I have a problem. I am trying to make an image gallery but I keep getting an error that this.current, this.size & this.initial are undefined, and therefore, the script cannot work. Please help me resolve this error. the following is the full script.
function gallery()
{
this.image = new Array(10);
this.initial = 1;
this.current = 0;
this.size = 10;
this.frame_height = 400;
this.frame_width = 600;
this.initialize=function()
{
if(document.images)
{
var count = 1;
for(count=1;count<=this.size;count++)
{
this.image[count] = new Image();
this.image[count].src = 'images/'+count+'.jpg';
}
}
divImg.id = "divImg";
divImg.setAttribute("Width",this.frame_width);
divImg.setAttribute("align","center");
divImg.setAttribute("margin","0px auto");
divBtn.id = "divBtn";
divBtn.setAttribute("align","center");
divBtn.setAttribute("backgroung-color","Black");
divBtn.setAttribute("color","White");
divBtn.style.margin = "0px auto";
divBtn.className ="btn";
pictureFrame.src = this.image[this.initial].src;
pictureFrame.setAttribute('Width',this.frame_width);
pictureFrame.setAttribute('Height',this.frame_height);
pictureFrame.name = 'img';
btnNext.innerHTML='NEXT';
btnPrevious.innerHTML='PREVIOUS';
btnLast.innerHTML='LAST';
btnFirst.innerHTML='FIRST';
btnFirst.onclick=this.first;
btnLast.onclick=this.last;
btnPrevious.onclick=this.previous;
btnNext.onclick=this.next;
myForm.appendChild(pictureFrame);
divImg.appendChild(myForm);
divBtn.appendChild(btnFirst);
divBtn.appendChild(btnPrevious);
divBtn.appendChild(btnNext);
divBtn.appendChild(btnLast);
pageBody.appendChild(divImg);
pageBody.appendChild(divBtn);
headerTag.appendChild(pageBody);
}
this.next=function()
{
alert(this.size);
alert(this.current);
if (this.current < this.size)
{
this.current +=1;
pictureFrame.src = this.image[this.current].src;
}
else
{
alert("This is the last image");
}
}
this.previous=function()
{
alert(this.current);
alert(this.initial);
if (this.current > this.initial)
{
this.current = this.current-1;
pictureFrame.src = this.image[this.current].src;
}
else
{
alert("This is the first image");
}
}
this.first=function()
{
this.current=this.initial;
pictureFrame.src = this.image[this.current].src;
}
this.last=function()
{
alert(this.size);
this.current=this.size;
pictureFrame.src = this.image[this.current].src;
}
};
var divImg= document.createElement('div');
var divBtn = document.createElement('div');
var btnFirst= document.createElement('button');
var btnNext= document.createElement('button');
var btnPrevious= document.createElement('button');
var btnLast= document.createElement('button');
var divTop = document.createElement('div');
var headerTag = document.getElementsByTagName('html')[0];
var pageBody = document.createElement('body');
var myForm=document.createElement("form");
var pictureFrame = document.createElement('img');
var pics=new gallery();
window.onload=pics.initialize();
You're expierencing an out of scope failure which is very common to people who are new to ECMAscript.
Every function has it's own execution context and each context in ECMA-/Javascript has its own this context variable. To avoid this, the most common way is to store a reference to the "outer" this context-variable in a local variable:
function gallery()
{
this.image = new Array(10);
this.initial = 1;
this.current = 0;
this.size = 10;
this.frame_height = 400;
this.frame_width = 600;
var self = this;
//...
this.initialize=function()
{
if(document.images)
{
var count = 1;
for(count=1;count<=self.size;count++)
{
self.image[count] = new Image();
self.image[count].src = 'images/'+count+'.jpg';
}
}
// ...
This will work in like every Javascript environment. In the meantime, there are "better" (other) ways to avoid this problem in ECMA. For instance, ECMAscript Edition 5 introduces the .bind() method which let you "bind" the reference from the this context variable to an object of your choice. Lots of javascript frameworks offer a pretty similar way of binding this to an object, even Javascript itself lets you do it with a little effort.
What jAndy said is correct, when the window object calls pics.initialise, this refers to window (this refers to the caller of the function, unless the function is anonymous).
However there is a simpler solution that you may prefer:
Instead of
var pics = new gallery();
window.onload = pics.initialize;
You can do:
var pics = new gallery();
window.onload = function() {
pics.initialize();
};
Because it is wrapped in an anonymous function, this will refer to the gallery instance, instead of window.
jAndy's suggestions are definitely more robust, but may be a bit difficult for someone still grappling with Javascript.

Categories

Resources