This code brakes my divs. Is it becasue of the global variable? - javascript

(function() {
if ( !window.BG || typeof window.BG !== 'object') {
window.BG = {};
}
var BG = window.BG;
BG.votdWriteCallback = function(json) {
var votd = json.votd;
document.write('<div>' + votd.text);
document.write(' </br><a target="_blank" href="' + votd.permalink +'">' + votd.display_ref + '</a>');
if (votd.audiolink) {
document.write(' <img alt="Listen to chapter" src="//www.biblegateway.com/assets/images/audio/sound.gif" border=0/>');
}
document.write('</div>');
};
window.BG = BG;
})();
Want to clean this script because for some reason it's breaking my HTML divs but I can't see where the problem is.

sorry, just saw now that im writing a extra div in the
document.write('</div>');
I know its bad practice to use document.write.
This is some old code that im trying to clean up

Related

Javascript function isn't recognized

I don't have many knowlege in javascript so I don't know what is the problem here,
I create divs dynamically in js and each div call a function when is clicked but the function is not recongized. This is part of the code
for (......) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + pag + ")'>" + temat + "</a>";
document.getElementById('menu').appendChild(listatema);}
}
"tema" is a text, the function "functest" has an argument "pag[aux]", this is a number.
The function is:
function functest(arg){
console.log(arg)
}
other alternative that i tried is change that: onClick='"+ functest(pag) +"':
i change the position of Quotation marks "" and the function work good but it is executed when the page is loaded, it don't wait to do click.
Your code should work if you're doing something like:
function functest(arg) {
console.log(arg);
}
for (var i = 0; i < 10; i++) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + i + ")'>" + i + "</a>";
document.getElementById('menu').appendChild(listatema);
}
<div id="menu"></div>
I would, however, recommend using addEventListener or setting the onClick handler on the document element object rather than setting the innerHTML. Note that setting innerHTML is not advised, especially when rendering user input. See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations. In your case, it probably isn't really an issue, but it's good practice to avoid it if you can :)
for (var i = 0; i < 5; i++) {
var wrapper = document.createElement("div");
var listatema = document.createElement("a");
listatema.textContent = i;
listatema.href = "javascript:void(0)";
listatema.addEventListener('click', function(e) {
console.log(this.i);
}.bind({ i : i }));
wrapper.appendChild(listatema);
document.getElementById('menu').appendChild(wrapper);
}
<div id="menu"></div>
onClick='functest(\""+ pag +"\")'
you forgot to quote the parameter.

Making use of a JSON attribute that doesn't always exist. Using jquery

I am writing a short script that connects to the LastFM api to get my last scrobbled song. The issue I am having is that the JSON version has an attribute for "now playing" which when you are currently listening to a song has the value of "true". However if there is no song playing the attribute doesn't exist at all.
This is the script I currently have and when I am listening to a song via spotify or iTunes etc... it works fine.
<p>
<p class="nowplaying"> <span class="track"></span> by <span class="artist"></span></p>
<p>
<script type="text/javascript">
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=JamesTaylor87&api_key=ADD-API-KEY-HERE&format=json', function(data) {
var artist = $(".artist"),
track = $(".track"),
np = $(".nowplaying"),
artistVal = data.recenttracks.track[0].artist["#text"],
trackVal = data.recenttracks.track[0].name,
nowplaying = data.recenttracks.track[0]["#attr"].nowplaying;
if(typeof nowplaying === "undefined"){
np.prepend("The last song I listened to was")
artist.append(artistVal);
track.append(trackVal);
} else {
np.prepend("I am currently listening to")
artist.append(artistVal);
track.append(trackVal);
}
});
</script>
However when I am not listening to anything I get the following error message (in safari) and nothing works:
undefined is not an object (evaluating 'data.recenttracks.track[0]["#attr"].nowplaying')
in chrome the error is displayed as follows:
Uncaught TypeError: Cannot read property 'nowplaying' of undefined
I have attempted to use an if statement for when it's undefined which hasn't worked and don't really know what else to try. Any help would be much appreciated.
Replace
data.recenttracks.track[0]["#attr"].nowplaying
with
data.recenttracks.track[0]["#attr"] && data.recenttracks.track[0 ["#attr"].nowplaying
That should stop the error occuring if data.recenttracks.track[0]["#attr"] is undefined
Try changing the line where you defined nowplaying to this:
nowplaying = (data.recenttracks.track[0]["#attr"]) ? data.recenttracks.track[0]["#attr"].nowplaying : undefined;
According to the chrome error, data.recenttracks.track[0]["#attr"] is undefined, which means you can't look for a property on it. You can use an if statement or a ternary to check whether this is defined before checking for its nowplaying property.
var attrs = data.recenttracks.track[0]["#attr"];
if (typeof attrs !== 'undefined') {
var nowPlaying = attrs.nowplaying;
}
Try this:
var track = data.recenttracks.track[0];
var nowplaying = track.hasOwnProperty('#attr') && track['#attr'].nowplaying;
I just built a very similar function for my site with Last.fm, and ran into this same problem. I was able to solve the problem by removing subsequent .nowplaying that you've included.
See below. Hope it's helpful!
// get the api
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOURUSERNAME&limit=1&api_key=YOURAPIKEY&format=json', function(data) {
var latesttrack = data.recenttracks.track[0]
var trackTitle = latesttrack.name
var trackArtist = latesttrack.artist["#text"]
// detect if the track has attributes associated with it
var nowplaying = latesttrack["#attr"]
// if nowplaying is underfined
if (typeof nowplaying === 'undefined') {
$('.nowplaying').html("Currently listening to nothing.")
} else {
$('.nowplaying p').html("Currently listening to" + trackTitle + " by " + trackArtist)
}
});
See it in action here: http://theadamparker.com/daily
<script type="text/javascript">
//<![CDATA[
var lastfm_api = 'http://ws.audioscrobbler.com/2.0/';
var lastfm_methods = 'user.getRecentTracks';
var lastfm_user = 'YOUR_USERNAME';
var lastfm_key = 'YOUR_APIKEY';
var lastfm_limit = '1';
var lastfm_json = lastfm_api + '?method=' + lastfm_methods + '&user=' + lastfm_user + '&api_key=' + lastfm_key + '&limit=' + lastfm_limit + '&format=json';
$.getJSON(lastfm_json, function(data) {
var html = '';
var song = data.recenttracks.track[0].name,
artist = data.recenttracks.track[0].artist["#text"],
url = data.recenttracks.track[0].url,
cover = data.recenttracks.track[0].image[0]['#text'];
html += '<p>' + song + ' by ' + artist + '<br /><br /><img src="' + cover + '" style="display: block; width: 96px; height: 96px;" /></p><p>Share on Twitter</p>';
$('#recent-tracks').append(html);
});
//]]>
</script>
<div id="recent-tracks"></div>

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

innerHTML = HTML & JQuery, JQuery doesn't execute

I am using jscript to insert HTML.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;}
The HTML part of the variable is passed just fine, but the JQuery animations do not work. If I hard code this in the HTML like below the animations work fine.
<div id="pluginWidgets2Div">
<a id="OrderTotals" href="">Order Totals</a>
<p id="OrderTotalText">Hiya<br />
Such interesting text, eh?</p>
<a id="FreightView" href="">View Freight</a>
<p id="FreightViewText" style="display: none">Hiya<br />
Such interesting text, eh?</p>
Another (3)
Menu item 4
One more (5)
<script>
$("#OrderTotals").click(function () {
$("#OrderTotalText").toggle("fast");
});
$("#FreightView").click(function () {
$("#FreightViewText").toggle("fast");
});
</script></div>
Thanks for your help.
.innerHTML doesn't execute script elements. You can use .html() in jQuery ...
Or do the sensible thing which is just running that code directly:
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
$('#OrderTotals').click(function () {
$('#OrderTotalText').toggle('fast');
});
}
There's a nice unobtrusive way to have this code waiting in the wings so that it will work. When inserting the HTML, skip the JavaScript - handle it separately.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
}
$(document).ready(function(){
$("#pluginWidgets2Div").on("click", "#OrderTotals", function () {
$("#OrderTotalText").toggle("fast");
});
});
The jQuery will apply to the HTML if/when it's inserted, and your HTML doesn't need to have any JavaScript in it.
You haven't closed the <script> tag:
orderTotalsHTML = "<a id='OrderTotals' href='#'>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});</script>";

Categories

Resources