I'm working on a Blogger widget, trying to rid it of any deprecated or bad practices (based what I read on Stack Overflow), such as document.write
This was working:
<script type="text/javascript">
function introductory(json) {
document.write('<div id="intro-wrapper">');
var i;
for (i = 0; i < json.feed.entry.length; i++) {
var introTitle = json.feed.entry[i].title.$t;
var introContent = json.feed.entry[i].content.$t;
var item = '<h2>' + introTitle + '</h2><p>' + introContent + '</p>';
document.write(item);
}
document.write('</div>');
}
</script>
<script src="https://MYBLOG.blogspot.com/feeds/posts/default/-/intro?max-results=1&alt=json-in-script&callback=introductory"></script>
It displays the title and content (wrapped up within h2 and p tags, respectively) of one single post ( ...max-results=1... ), labeled "intro" ( .../-/intro?... ) by means of Blogger labels.
I've tested various alternatives, lining up my html elements prior to the js, then using getElementById, followed by either innerHTML or appendChild, or even lining up the elements inside the js, by means of createElement, but to no avail, really. Would it be possible for anyone to point me to the right direction?
P.S. I can hardly copy and paste all of my attempts in this question. There have been dozens of them, as I'm more or less clueless when it comes to javascript and I'm just experimenting my way forwards, so I've opted for merely posting the code that is actually working and asking for an alternative that does not utilize document.write, if that's indeed "bad practice".
I greet you at the beginning about trying to rid document.write
Create an element with a unique id before your JS code in the document, then select this element by its id getElementById and add your content to it using innerHTML
<div id="intro-wrapper"></div>
<script type="text/javascript">
function introductory(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var introTitle = json.feed.entry[i].title.$t;
var introContent = json.feed.entry[i].content.$t;
item += '<h2>' + introTitle + '</h2><p>' + introContent + '</p>';
}
document.getElementById('intro-wrapper').innerHTML=item;
}
</script>
<script src="https://MYBLOG.blogspot.com/feeds/posts/default/-/intro?max-results=1&alt=json-in-script&callback=introductory"></script>
You can also use document.createElement instead of document.write.
Here is working example -
<script>
function introductory(json) {
var RecentPostContainer = document.createElement('div');
RecentPostContainer.className = 'RecentPostContainer';
for(i = 0; i < json.feed.entry.length; i++) {
var PostContainer = document.createElement('div');
PostContainer.className = 'PostContainer';
var PostTitle = document.createElement('h2');
PostTitle.className = 'PostTitle';
var PostTitleText = document.createTextNode(json.feed.entry[i].title.$t);
PostTitle.appendChild(PostTitleText);
PostContainer.appendChild(PostTitle);
var PostContent = document.createElement('div');
PostContent.className = 'PostContent';
PostContent.innerHTML = json.feed.entry[i].content.$t;
PostContainer.appendChild(PostContent);
RecentPostContainer.appendChild(PostContainer);
}
document.getElementById('RecentPostContainer').insertAdjacentHTML('afterend', RecentPostContainer.outerHTML);
}
</script>
<script id='RecentPostContainer' src="https://blogger.googleblog.com/feeds/posts/default/?max-results=1&alt=json-in-script&callback=introductory"></script>
Related
Here's a simple script that displays two latest posts under a certain label (in this example, the label "main"), in some section of a Blogger blog.
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML7").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?max-results=2&alt=json-in-script&callback=mainposts"></script>
Note that HMTL7 is the id that has been automatically assigned by Blogger to my HTML/Javascript-widget, which constitutes a div element by itself.
I have intentionally skipped including any post title variable in the script, so I'm just displaying the posts' content - no more, no less.
What I'd like to do is have two of these scripts for two different sections of my blog, where the second one would omit the two latest posts under the "main" label (same for both scripts), since they are already displayed by means of the first script.
What would I have to add to the second script to achieve this?
Add the start-index query parameter in the script src and initialize it from 3 (as the 1st and 2nd post would already be shown via the first instance of the code in the other section. The new code will look like -
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML99").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?start-index=3&max-results=2&alt=json-in-script&callback=mainposts"></script>
The exact ID of HTML widget will depend on your blog (mainly it will be different from HTML7)
Initialize for loop variable with 2 var i = 2; and maximum results 4 max-results=4
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 2; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML7").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?max-results=4&alt=json-in-script&callback=mainposts"></script>
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.
I'm currently working on a dealer search for my company. I want to add some tabs, so that the cutomers can filter the dealers per state. This means that the divs for the states are created dynamically, because the information comes from a CSV file.
I add the information like this:
function erzeugenTab() {
var $tabsDiv = $("#mapstabs");
var linkList ='';
var divRegion ='';
var linkZahl = 1
for (var i = 0; i < unique.length - 1; i++) {
linkList = linkList + "<li>" + unique[i] + "</li>" ;
divRegion = divRegion + "<div id =\"tabs"+linkZahl+"\">Test123</div>";
linkZahl = linkZahl + 1;
}
linkList = linkList + "</ul>";
$tabsDiv.append(linkList);
$tabsDiv.append(divRegion);
$(function() {
$('#mapstabs').tabs();
});
}
However, no tabs are apearring. You can se it here.
Any idea what I"m missing?
Can you try removing the $ on $tabsDiv turning it into just var tabsDiv?
Also, I do not see an open ul tag
Can you try by removing function()?
$(function() {
$('#mapstabs').tabs();
});
to
$('#mapstabs').tabs();
I want to insert </div><div id = '2'> to my html page
This is current code:
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
This is code I want to be after insert:
<body>
<div id='1'>
<p>abc1</p>
</div>
<div id='2'>
<p>abc2</p>
</div>
</body>
My javascript code is
var bodyTag = document.getElementsByTagName("body")[0];
var divTag = bodyTag.getElementsByTagName("div")[0];
var pCount = divTag.getElementsByTagName("p").length;
var str = '</div><div id = "2">';
var insert_pos = 1;
for(var i = 0 ; i < pCount; i++)
{
if(i != insert_pos)
{
s += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
}
else
{
s += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
s += str;
}
}
I used javascript to insert with method innerHTML but it inserts only <div id = '2'>, </div> is not inserted.
Please help me! Thank you very much!
Try this : You can make use of .after() and .append() as shown below
$(function(){
//add div2 after div1
$('#1').after('<div id="2"></div>');
//append last p to div2
$('#2').append($('#1 p:last'));
});
JSFiddle Demo
var bodyTag = document.getElementsByTagName("body")[0];
var divTag = bodyTag.getElementsByTagName("div")[0];
var pCount = divTag.getElementsByTagName("p").length;
var str = '<div>';
var insert_pos = 1;
for(var i = 0 ; i < pCount; i++)
{
if(i == insert_pos)
{
str += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
}
}
str+='</div>';
bodyTag.innerHTML+=str;
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
I think this could fulfill.
var pEls = document.getElementsByTagName('p'),
parentDivEl = document.getElementById('1'),
targetPEl = parentDivEl.removeChild(pEls[1]);
var divEl = document.createElement('div');
divEl.id = "2";
divEl.appendChild(targetPEl);
parentDivEl.parentNode.insertBefore(divEl, parentDivEl.nextSibling);
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
Using Javascript, here you go...
var pEls = document.getElementsByTagName('p'),
parentDivEl = document.getElementById('1'),
targetPEl = parentDivEl.removeChild(pEls[1]);
var divEl = document.createElement('div');
divEl.id = "2";
divEl.appendChild(targetPEl);
parentDivEl.parentNode.insertBefore(divEl, parentDivEl.nextSibling);
This one is interesting. I originally tried to use the insertAdjacentHTML function to insert the string '</div><div id="2">' after the first <p>, but strangely, the Dom rearranges these divs automatically to be '<div id="2"></div>'.
So, the next best option is to just do it manually. I'm not sure if this will work in your case, but it does output the desired result with less javascript.
Check out this fiddle.
http://jsfiddle.net/justinbchristensen/k2y2uggj/
var div1 = document.getElementById('1');
var ps = div1.children;
div1.removeChild(ps[1]);
div1.insertAdjacentHTML('afterend','<div id="2"><p>abc2</p></div>');
1) Get the div by its ID, assign it to a variable 'div1'
2) Access the 2 child <p> of the div and assign them to 'ps'
3) Remove the second <p>
4) Insert the entire second <div> with its child <p>
Let me know if this will work for your situation. If not, I'm sure we can come up with something more creative.
Thank you very much. I want to save the process time so I find the way to insert code like that. But it seems no way to insert. So, the right way to do is Moving the childs in this div to another. Thanks for your solution :)
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