What I am trying to do below since I don't have access to the PHP to my site, I am using this code to work around it. It will search for any links containing the two listed below. one from youtube with the /watch? in it and the other from youtube with just the /v in the url. It also is searching the any embedded elements. Problem is when I run the script it breaks all the other codes because of the error.
Uncaught TypeError: Cannot call method 'replace' of undefined
Which is a pain in the butt! So I took it over to FF, says variable WT is not defined clearly it is though. Well it may not be since I used it outside the scope of the if statement. I'm not sure how to ensure if the link exist run the code. As well as if the Embed exist run the code too. These will be in my users post and want them automatically changed to work with my fancybox.
Here is a live example
Its the copied markup from my page with a quick linked CSS so don't mind the buggy look.
$(function() {
//if link contains /watch?
var t = $('.entry-content div div a[href*="youtube.com/watch?"]').attr('href');
if(typeof t !== "undefined") {
//do nothing don't run the script below
} else {
var d = $('.entry-content div div a[href*="youtube.com/watch?"]');
var newsrc = t.replace('watch?','');
var asrc = newsrc.replace('=','/');
var g = asrc.replace('http://www.','http://img.');
var s = g.replace('v','vi');
d.attr('class','ez_video');
d.attr('href', asrc).html('<img src="'+ s +'/0.jpg"/>');
}
//if link contains /v
var wt = $('.entry-content div div a[href*="youtube.com/v"]').attr('href');
if(typeof wt !== "undefined") {
//do nothing don't run script below
} else {
var wd = $('.entry-content div div a[href*="youtube.com/v"]');
var o = wt.replace('http://www.','http://img.');
var v = o.replace('v','vi');
wd.attr('class','ez_video');
wd.attr('href', v).html('<img src="'+ v +'/0.jpg"/>');
}
//if embeded file
var src = $('.entry-content').find('embed').attr('src');
if (typeof src !== "undefined") {
//do nothing again unless true run script below
} else {
var qload = src.replace('http://youtube.com/v/','');
var y = src.replace('http://','http://img.');
var imgsrc = y.replace('v','vi');
$('embed').before('<a class="ez_video" id="'
+ qload +'" href="'+ src +'"><img src="'
+ imgsrc +'/0.jpg" tile="" alt=""/></a>');
$('embed').remove();
}
//Now make all work with the fancybox
$('.ez_video').fancybox({
'autoScale' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'width' : 854,
'height' : 480,
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
});
You are comparing it to a string of undefined while you should compare it the actual reserved word:
if(typeof wt !== undefined)
You can also do:
if(wt !== "undefined")
BTW, what you are doing is, if it is not undefined - do nothing, else - do something, is this really what you want?
Related
Hi i get a JS error in my browser inspector. But i dont understand whats wrong with my Jquery code. And why he consider this variable as undefined ... Could someone help me ?
The code works well; but i would prefer to remove the error:
Uncaught TypeError: varposlist is undefined
This is my js code:
$(function(){
var pane = $('.scroll-pane');
pane.jScrollPane({
});
var api = pane.data('jsp');
if(typeof localStorage!='undefined') {
//Get var from local storage
var menu = sessionStorage.getItem("menu");
var yposistock_rule = sessionStorage.getItem("yposistock_rule");
//Check menu view mode
if(menu == "arbo") {
// defined top from a#on anchor
var varposchapter = $('a#on_menuchapter').offset();
//add - 285 to put at same level than title
var vartop1 = varposchapter.top -285 -yposistock_rule;
if(scrollauto_rule == "oui") {
sessionStorage.removeItem("yposistock_rule");
};
api.scrollTo(0, vartop1);
return false;
}
else{
// defined top from a#on anchor
var varposlist = $('a#on_menulist').offset();
//add - 285 to put at same level than title
var vartop2 = varposlist.top -285 -yposistock_rule;
if(scrollauto_rule == "oui") {
sessionStorage.removeItem("yposistock_rule");
};
api.scrollTo(0, vartop2);
return false;
}
}
});
Any idea ? Thanks a lot.
The only thing I can think of is this line:
$('a#on_menulist').offset();
The # selects the element with the same ID. Unless you have an element with id=on_menulist, this code cannot find the id which then cannot find the offset.
I'm trying a week to find a way for the following problem.
I have a 1.php file
//bowser.js And fingerprint2.js are included I ignored them here
function HttpRequest(e) {
var i = !1;
i || "undefined" == typeof XMLHttpRequest || (i = new XMLHttpRequest), i && (i.open("GET", e, !1), i.send(null), embedpage(i))
}
function embedpage(e) {
(-1 == window.location.href.indexOf("http") || 200 == e.status) && 0 != e.responseText && document.write(e.responseText)
}
browser = bowser.name;
browserv = bowser.version;
bowser.windows ? os = "windows" : bowser.mac ? os = "mac" : bowser.linux ? os = "linux" : bowser.android ? os = "android" : bowser.ios ? os = "ios" : bowser.windowsphone ? os = "windowsphone" : bowser.chromeos ? os = "chromeos" : bowser.blackberry ? os = "blackberry" : bowser.firefoxos ? os = "firefoxos" : bowser.webos ? os = "webos" : bowser.tizen ? os = "tizen" : bowser.bada ? os = "bada" : bowser.sailfish && (os = "sailfish");
new Fingerprint2().get(function(result) {
url = 'http://gotoo.cf/2.php?tag=<?php echo $_GET["tag"] ?>&browser=' + browser + '&bv=' + browserv + '&os=' + os + '&secure=' + result;
HttpRequest(url);
});
2.php make html to show banners
when I use it in my blog by:
<script type="text/javascript" src="http://gotoo.cf/1.php?tag=6&width=120&height=240"></script>
it reload all page.
you can see there
http://adseo.blogfa.com/
but when I use HttpRequest(url);out of new Fingerprint2().get(function(result) { it works perfectly.
but the big problem is url var.( because ir can not be accessible out of function)
global var and cookie does not work because Fingerprint2().get(...) is asynchronous.
I want to know why HttpRequest(url); treat like that?
and how to store fingerprint2 result like function and use it whereever I want.
Or some method that you understand.
The problem is this here:
document.write(e.responseText)
The document.write will make the browser create a new document and then insert the passed text replacing all current content of the page. Instead, you need to tell the browser to insert the text into a specific part of the already existing document.
For example:
document.body.insertAdjacentHTML('afterbegin', e.responseText)
will insert the banner at the beginning of the page. In reality, you would want to use a more specific place inside the page. Use a div with a specific id as a placeholder and then replace the content of this div with the text retrieved via the asynchronous HTTP call.
Some more explanations:
When JavaScript code uses document.write() while the page is still being loaded, the content will be written at the current position of the currently loaded document. However, since you execute your code asynchronously using Fingerprint2.get(), the code is executed after the page has finished loading and document.write() will then lead to the browser starting with a new document.
From the documentation:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
How to solve your dilemma:
In your code, first add a div with a random unique identifier to the document using document.write. Then, in the callback function, that is called from Fingerprint2.get(), add the content into that div.
See the following example set of files that show the mechanism:
A.html
<html>
<body>
<script src="Banner.js"></script>
<div>Static Content</div>
<script src="Banner.js"></script>
</body>
</html>
B.html
<div>
Some Banner!
</div>
Banner.js
// Note that HttpRequest and embedpage are declared inside insertBanner
// so that they can access the aRandomName parameter
function insertBanner(aRandomName)
{
// First add a placeholder div with the given random name
document.write('<div id="' + aRandomName + '"></div>');
// Then asynchronously call HttpRequest()
// We use setTimeout where then FingerPrint2.get() would be used
url = "B.html";
setTimeout(
function()
{
HttpRequest(url);
}
, 100
);
function HttpRequest(e)
{
i = new XMLHttpRequest;
i.onreadystatechange = embedpage;
i.open("GET", e, true); // Use HttpRequest asynchronously to not block browser
i.send();
}
function embedpage(e)
{
if(this.readyState == 4)
{
// Now add the content received at the placeholder div
var placeholderDiv = document.getElementById(aRandomName);
placeholderDiv.innerHTML = this.responseText;
}
}
}
// First get a random name for the banner div
var randomName = 'GotooCF' + makeid();
// Now call the banner using the random name
insertBanner(randomName);
// makeid() Taken from http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
As NineyBerry said, the main problem is document.write()
so I used :
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
In all browser except Firefox it works.
But still need to be modifiled,
I think we should make a new document.write function for these situations.
thanks
im currently creating a site where i want people to be able to change the background image. i have the script to change working just fine, but i'd like to include a "remember" feature.
here's my javascript code:
$(document).ready(function(){
var body = $(document.body);
$('#backgrounds').bind('change', function(event){
var bg = $(this).val();
if(bg == null || typeof bg === 'undefined' || $.trim(bg) === '')
body.css('background-image', '');
else
body.css('background-image', "url('" + bg + "')");
});
});
how would i add a "remember" feature to this?
You can store the background URL in the local storage if you're only targeting modern browsers.
Where you've declared var bg = $(this).val(), add a newline beneath it that should be like localStorage.setItem('bg', bg);.
Then underneath var body = $(document.body);, write: if( localStorage.getItem('bg') ) { body.css('background-image', "url('" + localStorage.getItem('bg') + "');"); }.
I decided to try a different approach to this problem. Instead of relying on a string I thought it would be more efficient for this specific issue to use the function location.path to determine the source of the album-cover. Here's what I only have so far:
The piece of HTML for the image:
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
The piece of Javascript I have:
var albumCover = document.getElementsByClassName('album-cover') // Get the album cover
var currentLink = location.pathname
var dictionary =
{ // location.pathname : image source for albumCover
'/music/King+Crimson/Red' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Red.jpg',
'/music/King+Crimson/Discipline' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Discipline.jpg'
}
Now here's the piece of the code that's incomplete:
if (currentLink === ''// first part of the dictionary)
{
albumCover.src = '' second part of the dictionary
};
else{};
Any help is welcome and thanks for reading, cheers.
Old Post:
a follow-up on a question I asked recently but I can't seem to be able to change the code to match what I'm looking for. The code occurs on the following website: link
I'm interested in changing the image source in the code below. However, the new image source is to be determined based on what the H1-element of that webpage contains.
<div class="g3 album-cover-wrapper album-cover-wrapper--no-cover " >
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
<section class="r add-top-margin remove-bottom-margin">
<div class="g4"> </div>
</section>
</div>
Now I thought it would be useful to use 'dictionary-list' like following:
if H1 contains the string 'Discipline'{img.src="newsource.jpg'};
Thanks for taking the time to read this, cheers!
Edit: here's a piece of code I tried but I'm guessing it needs more info for it to actually work.
var headerDef = document.getElementsByTagName('h1'),
var img = document.getElementsByClassName('album-cover');
if (headerDef === 'Red')
{
img.src = "newsource.jpg";
};
else{};
A few examples of how the list will be:
//string in H1 : new image source for the 'album-cover'-class image
'Discipline' : 'http://ecx.images-amazon.com/images/I/41kcnkbxS-L._SL500_AA300_.jpg',
'Red' : 'http://img.noiset.com/images/album/king-crimson-red-4-cd-cover-31985.gif',
etc...
It's a list for which I'd have to manually add each instance of a page having a specific H1-string.
I'd suggest the following:
var map = {
'red': 'oh my gods!',
'blue': 'blue? Really..?'
};
function influenceImage(source, map) {
if (!source || !map) {
return false;
}
else {
var text = source.textContent || source.innerText;
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
return map[word];
}
}
}
}
// in real life, with an image use:
// imageNode.src = influenceImage(document.getElementsByTagName('h1')[0], map);
document.getElementById('test').title = influenceImage(document.getElementsByTagName('h1')[0], map);
JS Fiddle demo.
In the demo I set the title attribute of an a element, but, of course, as noted in the comment simply set the src attribute of an image node.
The above changed, slightly (within the else {...}, to make it a case-insensitive search/match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
JS Fiddle demo.
And another edit, again within the else {...}, in order to add a default option in case there's no word-match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
// we only get here if the `for` loop and the `if` doesn't throw out a match.
return 'default string';
JS Fiddle demo.
Using javascript I'm trying to load images not on the current page (from an array of image links) and if they are large enough, add them to an array. I'm executing this after the current page has loaded, though a bookmarklet, or firebug console. Using FF.
The closest I've come is the below, but this does not seem to work, and I'm guessing this is because the size test is running before the images have loaded. Apparently my attempt to fix this with 'onload' does not work. How can I fix this up, or is there a better/simpler way to accomplish this task?
(function() {
//create array for the images
var imageArray = new Array();
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
//dispImage = '<img src=' + x.src + '><br>';
//document.write('<center>' + dispImage + '</center>');
}
return true;
}
//given an array of imageLinks:
for (x in imageLinks){
//create an image form link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = loadIfBig(im);
}
//view results:
for (x in imageArray){
disp_image = '<img src='+imageArray[x].src+'><br>';
document.write('<center>'+disp_image+'</center>');
}
})();
Update:
Thanks! sure you're right and I'm missing something stupid here, but I made the change you suggested, and then pulled writing the elements into loadIfBig, but it doesn't seem to be executing that function. current code below, including a couple sample input links:
(function() {
var imageArray = new Array();
var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
dispImage = '<img src=' + x.src + '><br>';
document.write('<center>' + dispImage + '</center>');
}
return true;
}
processImages = function(){
for (x in imageLinks) {
//create an image from link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = function(){
loadIfBig(this);
}
}
}
})();
Your fix doesn't work because you're actually executing it immediately.
im.onload = loadIfBig(im) is actually running the function.
What you can do is something like:
im.onload = function() {
loadIfBig(this);
}
Another problem is the fact that you're running through the array of big images before the onload callbacks have actually executed. That needs to be stuck in a different function and called once all the onloads are done.