This code is being used on a Chrome Extension.
When I call the "showOrHideYT()" function, I get a
"Uncaught ReferenceError: showOrHideYT is not defined | (anonymous
function) | onclick"
This code will search for youtube links in a page, and it will add a button (it's really a div with an event) next to the link to show the iframe with the embedded video, pretty much like Reddit Enhancement Suite. Consider the code, per se, incomplete. I just want to know what am i missing when i call the "showOrHideYT(frameZES12345)" function.
if needed, i can provide manifest.json.
Thanks
function showOrHideYT(id)
{
var YTvidWidth = 420;
var YTvidHeight = 315;
frameYT=getElementById(id);
console.log(frameYT.style.visibility);
if (frameYT.style.visibility == "hidden")
{
frameYT.style.width = YTvidWidth+"px";
frameYT.style.height = YTvidHeight+"px";
frameYT.style.visibility = "visible";
}
if (frameYT.style.visibility == "visible")
{
frameYT.style.width = "0px";
frameYT.style.height = "0px";
frameYT.style.visibility = "hidden";
}
};
// DOM utility functions
function insertAfter( referenceNode, newNode ) {
if ((typeof(referenceNode) == 'undefined') || (referenceNode == null)) {
console.log(arguments.callee.caller);
} else if ((typeof(referenceNode.parentNode) != 'undefined') && (typeof(referenceNode.nextSibling) != 'undefined')) {
if (referenceNode.parentNode == null) {
console.log(arguments.callee.caller);
} else {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
}
};
function createElementWithID(elementType, id, classname) {
obj = document.createElement(elementType);
if (id != null) {
obj.setAttribute('id', id);
}
if ((typeof(classname) != 'undefined') && (classname != '')) {
obj.setAttribute('class', classname);
}
return obj;
};
///////////////////////////////////////
$(document).ready(function() {
var vidWidth = 420;
var vidHeight = 315;
var linksSemID = document.getElementsByTagName("a") ;
for (var i = 0; i < linksSemID.length; i++){
if (/id=$/.test(linksSemID[i].href)) links[i].href += "1";
}
i=0;
var youTubeRegExp = /(?:v=)([\w\-]+)/g;
var forEach = Array.prototype.forEach;
var linkArray = document.getElementsByTagName('a');
forEach.call(linkArray, function(link){
linkArray.id="zes" + i++;
var linkTarget = link.getAttribute('href');
if (linkTarget!=null)
{
if (linkTarget.search(youTubeRegExp) !=-1)
{
console.log (linkTarget);
idVideo=linkTarget.match(/(?:v=)([\w\-]+)/g);
//idVideo = idVideo.replace("v=", "");
//add buton
botaoMais = document.createElement('DIV');
botaoMais.setAttribute('class','expando-button collapsed video');
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
insertAfter(link, botaoMais);
//add iframe
ifrm = document.createElement('IFRAME');
ifrm.setAttribute('src', 'http://www.youtube.com/embed/'+ idVideo);
ifrm.style.width = '0px';
ifrm.style.height = '0px';
ifrm.style.frameborder='0px';
ifrm.style.visibility = 'hidden';
ifrm.setAttribute('id', 'frameZES' + i);
insertAfter(link, ifrm);
}
}
});
});
When you use setAttribute with a string, the event will be executed in the context of the page. The functions which are defined in a Content script are executed in a sandboxed scope. So, you have to pass a function reference, instead of a string:
Replace:
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
With:
botaoMais.addEventListener('click', (function(i) {
return function() {
showOrHideYT("frameZES"+ i);
};
})(i));
Explanation of code:
(function(i) { ..})(i) is used to preserve the value of i for each event.
Inside this self-invoking function, another function is returned, used as an event listener to click.
I see that you are using jQuery in your code. I personally think if we are using a library like jQuery, then we should not mix the native javascript code and jQuery code.
You can use jQuery bind to bind your the functions you need to call on dom ready.
Read below to know more.
suppose you want to call a javascript function on a button click, Here is the HTML for the same.
<div id="clickme">
<input id= "clickmebutton" type="button" value = "clickme" />
</div>
suppose "test" is the function you need to call, here is the code for test function.
function test() {
alert("hello");
}
you now need to bind the test function on the button click.
$(document).ready(function() {
$("#clickmebutton").bind("click", function(){
// do what ever you want to do here
test();
});
});
Related
I'm currently working on counting the number of opened tabs on my application. but my problem is it seems that my script won't detect events onload. Here is my code.
I'm using HTML5 web storage and native js. I'm not using jQuery to understand more on native js.
(function(w) {
function Tabz(win, key) {
this.name = '';
this.storageKey = key;
if(win.name != '')
this.name = win.name;
else {
var windowArr = JSON.parse(localStorage.getItem(key)) || [];
this.name = "tabz_"+ windowArr.length;
win.name = this.name;
windowArr.push(this.name);
localStorage.setItem(this.storageKey, JSON.stringify(windowArr) );
}
}
Tabz.prototype.getStorage = function() {
return localStorage.getItem(this.storageKey);
}
Tabz.prototype.removeWindow = function() {
//remove window function here
}
var newWindow = new Tabz(w, 'counter');
window.load = function() {
var count = JSON.parse(newWindow.getStorage()).length;
alert(count!); // this wont execute so that I can check the count.
}
})(window);
Your issue is on this line:
window.load = function() {
This will add a load property to the window, not add an event listener. I think you are looking for onload.
window.onload = function() {
Incidentally, using event properties is considered bad-practice. Using addEventListener would be better.
window.addEventListener("load", function(){
//Do stuff...
});
I am calling the parent function like window.parent.functionname(); from the child page. How can i call the window.child.function() from the parent page to child page.
Any help is appreciated.
Give your iFrame an id and try
document.getElementById("iFrameId").contentWindow.functionname()
This works even when you have multiple iFrames in the same page irrespective of their order.
Do you have an iframe?
Do something like that:
window.frames[0].contentDocument.functionname();
Parent page
var windowRef = null;
function openChildWindow() {
if ((windowRef != null) && (windowRef.closed == false)) {
if (windowRef.closed == false) windowRef.close();
windowRef = null;
}
var windowUrl = 'ChildPage.aspx';
var windowId = 'NewWindow_' + new Date().getTime();
var windowFeatures = 'channelmode=no,directories=no,fullscreen=no,' + 'location=no,dependent=yes,menubar=no,resizable=no,scrollbars=yes,' + 'status=no,toolbar=no,titlebar=no,' + 'left=0,top=0,width=400px,height=200px';
windowRef = window.open(windowUrl, windowId, windowFeatures);
windowRef.focus();
// Need to call on a delay to allow
// the child window to fully load...
window.setTimeout(callChildWindowFunction(), 1000);
}
function callChildWindowFunction() {
if ((windowRef != null) && (windowRef.closed == false)) windowRef.childWindowFunction();
}
Child Page
function childWindowFunction() {
alert('Hello from childWindowFunction()');
}
var win = null;
function openAndCall(id){
if (win!=null && win.closed==false){
win.close();
}
win = window.open("/somePage");
win.onload = function(){
win.callSome(id);
};
}
HTML part:
foo
JS part:
function callme() {
var me = ?; //someway to get the dom element of the a-tag
$(me).toggle();
}
in the JS part can i somehow get the a-tag that this function was called from?
i know i could just pass it as a parameter, but this function is used many many times on a page and i want to avoid putting the parameter everywhere.
thanks!
Since you are using an onclick attribute (BAD!) you have to pass that into the function.
onclick="callme(this); return false;"
and the js:
function callme(el) {
var $me = $(el);
$me.doSomething();
}
Another option is to set the context of the function using .call().
onclick="callme.call(this,event)"
and the js
function callme(event) {
event.preventDefault();
$(this).doSomething();
}
I have a simple JS function for that
function getEventTarget(event) {
var targetElement = null;
try {
if (typeof event.target != "undefined") {
targetElement = event.target;
}
else {
targetElement = event.srcElement;
}
// just make sure this works as inteneded
if (targetElement != null && targetElement.nodeType && targetElement.parentNode) {
while (targetElement.nodeType == 3 && targetElement.parentNode != null) {
targetElement = targetElement.parentNode;
}
}
} catch (ex) { alert("getEventTarget failed: " + ex); }
return targetElement;
};
in your html
foo
in your function
function callme(event) {
var me = getEventTarget(event); //someway to get the dom element of the a-tag
$('#'+ me.id).toggle();
}
getEventTarget() will bring back the whole dom object which you can manipulate as you please, or has been said already by other users you can just use
function callme(event) {
$(this).toggle();
}
send this parameter to your function.
foo
function callme(me) {
$(me).toggle();
}
better dont use onlcick in html markup
$(document).ready(function() {
$("a").click(callme);
})
function callme() {
var me = this;
$(me).toggle();
}
I am using the ajaxify.js plugin https://github.com/browserstate/ajaxify to load content dynamically.
I have a number of click functions that I bind on document ready, but have to additionally put those functions inside of my ajax load function to re-bind the click events to the newly added content. I had tried using a single set of live functions previously but they didn't work.
Anyway I have the following code twice, once inside of a document.ready(function(){ }) and once again inside of ajaxify.js after the content loads.
I know it's superfluous, but I'm not sure of how to go about writing the functions just once so I can "include" them elsewhere. How can I optimize these functions so I can consolidate them and use them over again in an efficient manner?
Thank you!
var $filterclear = $('.filters .filter-clear'),
filtercount = $filterclear.length,
$searchedfor = $('.searched-for'),
is_search = $searchedfor.length;
$filterclear.bind('click', function(){
var $me = $(this);
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
$(this).addClass('filter-out').fadeOut('fast');
} else {
$(this).addClass('filter-out').fadeOut('fast');
}
if($me.hasClass('clear-all') || filtercount == 1) {
$filterclear.addClass('filter-out').fadeOut('fast');
if(is_search !== 0) {
$('.filters').fadeOut();
}
}
});
$('.tag.remove-term').bind('click', function(){
var $me = $(this),
mytext = $me.text(),
$myfilter = $('.filters .filter-clear:contains("'+ mytext +'")');
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
$myfilter.addClass('filter-out').fadeOut('fast');
} else {
$myfilter.addClass('filter-out').fadeOut('fast');
}
});
$searchedfor.find('.filter-clear').bind('click',function(){
$searchedfor.fadeOut();
});
Defining a new function should work (I didn't test it):
var $filterclear = $('.filters .filter-clear'),
filtercount = $filterclear.length,
$searchedfor = $('.searched-for'),
is_search = $searchedfor.length;
var doSomething($myfilter) {
if(filtercount == 3) {
$('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast');
}
$myfilter.addClass('filter-out').fadeOut('fast');
};
$filterclear.bind('click', function() {
var $me = $(this);
doSomething($me);
if($me.hasClass('clear-all') || filtercount == 1) {
$filterclear.addClass('filter-out').fadeOut('fast');
if(is_search !== 0) {
$('.filters').fadeOut();
}
}
});
$('.tag.remove-term').bind('click', function(){
var $me = $(this),
mytext = $me.text(),
$myfilter = $('.filters .filter-clear:contains("'+ mytext +'")');
doSomething($me);
});
$searchedfor.find('.filter-clear').bind('click',function(){
$searchedfor.fadeOut();
});
I'm having trouble with some javascript which uses getElementById. It works fine in FF, Safari and Chrome, but IE(8 - haven't tried others) bails out.
The relevant bit of html is a div called topnav:
<div id="topnav">
... some HTML ...
<div>
<div id="sub_1" class="lowernav">
... some HTML ...
</div>
<div id="sub_2" class="lowernav">
... some HTML ...
</div>
In my javascript, I want to find topnav. The full code (up to where it bails) is this:
<script>
window.onload = init();
function init() {
// Show current menu
showCurrentMenu();
}
function showCurrentMenu() {
hideMenus(); // Hide all menus and then show the current one
topnav = document.getElementById('topnav');
... rest of code ...
}
function hideMenus() {
var divlist = document.getElementsByTagName('div');
for(var ii=0; ii<divlist.length; ii++) {
if(divlist[ii].className != divlist[ii].className.replace('lowernav','')) {
divlist[ii].className += ' hidden';
}
}
}
... then some other code it hasn't reached yet...
Am I doing something wrong here? It may well be something really obvious, but for the life of me, I can't see it! All advice is much appreciated.
ETA: Ok, here's the whole code, as it currently stands:
<script>
window.onload = init;
function init() {
// Show current menu
showCurrentMenu;
// Attach 'onmouseover' event to main menu items
topnav = document.getElementById('topnav');
// Get all items in list
var menulist = topnav.getElementsByTagName('a');
for(var ii=0; ii<menulist.length; ii++) {
menulist[ii].onmouseover = showMenu;
}
document.getElementById('mainHomeNav').onmouseout = restoreMenu;
}
function restoreMenu(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
if (targ.id == "mainHomeNav") {
showCurrentMenu;
}
}
function hideMenus() {
var divlist = document.getElementsByTagName('div');
for(var ii=0; ii<divlist.length; ii++) {
if(divlist[ii].className != divlist[ii].className.replace('lowernav','')) {
divlist[ii].className += ' hidden';
}
}
}
function showCurrentMenu() {
hideMenus;
topnav = document.getElementById('topnav');
// Get all items in list
var menulist = topnav.getElementsByTagName('a');
for(var ii=0; ii<menulist.length; ii++) {
if(menulist[ii].className != menulist[ii].className.replace('thisSection','')) {
var thisid = menulist[ii].id;
var thissubmenu = document.getElementById(thisid + '_sub');
thissubmenu.className = thissubmenu.className.replace(/hidden/g,'');
}
}
}
function showMenu() {
hideMenus;
// show this menu
var submenu_id = this.id + '_sub';
var submenu = document.getElementById(submenu_id);
submenu.className = submenu.className.replace(/hidden/g,'');
}
</script>
The problem is
window.onload = init();
This will call the init function immediately, and then use its return value as the page's onload function. You need:
window.onload = init;
which will call the init function only after the page has fully loaded.
I found the problem - I didn't have 'var' in front of 'topmenu'.
So instead of
topnav = document.getElementById('topnav');
it should have been
var topnav = document.getElementById('topnav');
Thanks everyone for the help.
Your problem lies in the following line:
window.onload = init(); // this will CALL init() and assign the return value
Since init doesn't return anything, window.onload will be undefined.
Now the reason for it not working in IE, but in other Browsers is that those other Browsers might already have parsed a part of the DOM and therefore the call to showCurrentMenu works.
But that could just as well break, since from a technical point of view the document is not guaranteed to be loaded, to fix that you have to assign the actual function reference to window.onload by doing:
window.onload = init;