document.createElement / document.body.appendChild not creating / writing div where executed - javascript

I have a div with the ID 'headercontent' and I have a script that will write a link amongst the others if javascript is enabled on the users system, but also has a backup using noscript just in case the user does not have javascript enabled.
The code runs fine and the 'a' element is written when executed but the problem is that the code is not written in the div it is executed in. It writes it outside of the 'headercontent' div and it ignores the class style completely, even though it is written in the rendered code. I'm not too worried about the styling/class because I can just add a style attribute to the element and get it written by javascript if necessary, but I'm more concerned about why its writing the code outside of this div.
My code is:
<div id="headercontent">
hey, this is a div.
This is a link
This is another link
<script type="text/javascript">
writeask()
function writeask() {
var writeaskbox = document.createElement('a');
writeaskbox.href = 'javascript:askbox()';
writeaskbox.className = 'button';
writeaskbox.innerHTML =
['Ask'].join(' ')
document.body.appendChild(writeaskbox);
}
function askbox(){
var askbox = document.getElementById('askbox')
if (askbox.style.display == 'none') {
askbox.style.display = 'block'
askbox.style.height = '150px'
} else {
askbox.style.display = 'none'
askbox.style.height = '0px'
}
}
</script>
<noscript>Ask</noscript>
</div>
How do I get the writeask() function to create this a element in the same div it is executed in? So that the final output is:
<div id="headercontent">
hey, this is a div.
This is a link
This is another link
Ask
</div>
Instead of:
<div id="headercontent">
hey, this is a div.
This is a link
This is another link
</div>
Ask
I'm still a beginner with javascript so I'm rather puzzled now. If anyone could help, that would be well appreciated.
Thank you in advance. Dan.

First of all, you are invoking writeask() before the function exists so, in this case you should do it the other way around. It should be:
function writeask() {}
function askbox(){}
writeask();
and then you are appending it to the body
document.body.appendChild(writeaskbox);
, not the div, as it should be
document.getElementById("headercontent").appendChild(writeaskbox);

Instead of
document.body.appendChild(writeaskbox);
use
document.getElementById("headercontent").appendChild(writeaskbox);

Instead of
document.body.appendChild(writeaskbox);
You should do the following:
document.getElementById('headercontent').appendChild(writeaskbox);

Related

Javascript - Click list element to load HTML page animation

Javascript novice here. I am working on a piece of code provided here - http://codepen.io/mariusbalaj/pen/beALH/
I'm trying to modify the behavior so that instead of just zooming in the list element when clicked, it should load a different html page within the animated frame.
$(document).ready(function() {
var $box = $('.box');
$('.metro li').each(function() {
var color = $(this).css('backgroundColor');
var content = $(this).html();
$(this).click(function() {
$box.css('backgroundColor', color);
$box.addClass('open');
$box.find('p').html(content);
});
$('.close').click(function() {
$box.removeClass('open');
$box.css('backgroundColor', 'transparent');
});
});
});
Can anyone point me to the right direction?
Update 1 :
I figured out that modifying the 'content' variable on the below line would change the content of the animated frame:
` $box.find('p').html(content);`
And if I change it to something like:
` $box.find('p').html('<h1>Test Page</h1>');`
It works as expected. However, I want the content to be different for each list element.
Is there an easy way of doing this per element? I am quite confused with the 'this' keyword.
You may be looking for this answer, if you want to open another HTML page:
how to change page from within javascript
If you're trying to open it WITHIN the animated frame, you should look into making some requests to the content of the new page/tile and filling that with content, which is answered here: How to get the response of XMLHttpRequest?
It all depends what you want to do, let us know :)

Activate hover action on a certain word

Okay, so this is something that has already been done so I know it's possible. What I'd like is that, when the user hovers the mouse on some word defined by the wordHoverAssign() function, something would get activated.
So, in a more concise manner: When the page is loaded the text I love potatoes! shows up on screen, created with HTML. Then the function wordHoverAssign("potatoes") is executed. What should happen then, when I hover the word potatoes, is that an alert message would pop up with, for example, this message You hovered the word!.
Is this possible? How would I go about doing it? I'd really like it if I didn't have to use any more frameworks/plugins. I'm using jQuery by the way.
Thank you.
My code so far (if you don't feel like setting it up):
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
//code here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I love potatoes!</p>
The following allows you to assign different function to any word inside the #content div. The associated function is called only when the specific word is hovered.
<div id="content">
I love potatoes!<br/>
She loves something else<br/>
The potatoes coming again.
</div>
<script>
window.wordsAssigned = {};
function wordHoverAssign(word,func){
wordsAssigned[word] = func;
}
wordHoverAssign('potatoes',function(){
alert('Patatoes hovered!');
});
wordHoverAssign('something else',function(){
alert('something else!');
});
$(function(){
var content = $('#content');
var html = content.html();
for(var word in wordsAssigned){
html = html.replace(new RegExp(word,"gm"),'<span onmouseover="wordsAssigned[\''+word+'\']()">'+word+'</span>');
}
content.html(html);
})
</script>
As per your need :contains('text') suits you better. see example:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( ":contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Here is Updated DEMO
But above code will alert twice because of hover event also bind with body, so my suggestion is use special tag. See following snippet:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( "p:contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Another DEMO for hover in p tag. It won't work on body hover.

Cannot load HTML in a div that was ajax'd in

Good afternoon, I am at a total loss on why this is happening. I have searched online and tried to understand what I'm doing wrong for 5+ hours and could find no solution. Here is the situation.
I have 3 pages (index.html, index.js, and stuff.html)
index.html is the main page and uses jQuery to load an HTML page into a div.
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="stuffHolder"></div>
<script type="text.javascript">
$(document).ready(function(){
$('#stuffHolder').load('stuff.html');
});
</script>
</body>
</html>
The stuff.html page loads just fine for me.
Inside the stuff.html I have 2 div's
1. One of the DIV's uses sprites as anchor tags to call a function named actOnStuff(options).
<div id="myStuff"><a class="myStuffSprite" href="Javascript:actOnStuff('newStuff')"><span>New Stuff</span></a></div>
<div id="yourStuff"><a class="yourStuffSprite" href="Javascript:actOnStuff('oldStuff')"><span>Old Stuff</span></a></div>
The other DIV is empty but will have innerHTML written to it later.
Inside index.js, which sits on the index.html page, I have a function
function actOnStuff(youSelected){
strHTML = "";
switch(youSelected){
case "newStuff":
strHTML += "<div id='newDIV'><span>You selected New</span></div>";
break;
case "oldStuff":
strHTML += "<div id='oldDIV'><span>You selected Old</span></div>";
break;
}
$('#placement').html(strHTML);
alert($('#placement').html());
}
My problem is that when I alert the innerHTML of the placement DIV it shows that the necessary DIV from the function as added in the alert. HOWEVER, nothing shows up in the placement DIV at all.
Any help you can provide would be wonderful as I am at a total loss as to what the problem is. Thanks in advance.
I'm not sure I can help solve the actual problem, but there's many issues and bad practices in your code that I'd like to point out for the greater good of the community.
Here's my take on your code:
HTML in body
<div id="stuff-holder"></div>
HTML in stuff.html
<div id="my-stuff">
<a class="my-stuff-sprite" href="#"><span>New Stuff</span></a>
</div>
<div id="your-stuff">
<a class="your-stuff-sprite" href="#"><span>Old Stuff</span></a>
</div>
Bad practice: CSS and HTML is most of the time not case-sensitive, so when naming IDs with camelcase such as fooBar, could create confusion with foobar or Foobar. Instead, use lowercase only and dash as separator (like in CSS).
JavaScript in index.js
I moved your ready function into index.js. I don't see a reason why you would want that in your HTML document when you already have a separate JavaScript file.
// Shorthand for ready
$(function(){
// Cache the selector
var $placement = $("#placement");
// Put function in the local scope so we don't clutter the global scope
function actOnStuff(youSelected) {
// Not declaring variables with var, makes it global (bad idea!)
var html = "";
switch (youSelected) {
case "my-stuff":
html += '<div id="new-div"><span>You selected New</span></div>';
break;
case "your-stuff":
html += '<div id="old-div"><span>You selected Old</span></div>';
break;
}
// Put new html in placement element
$placement.html(html);
// Use console.log to debug your code instead of alert
console.log($placement.html());
}
// Load stuff into stuff holder and bind event handler to load event
$("#stuff-holder")
.load("stuff.html")
.on("load", function() {
// After it has loaded, bind click events
$("#my-stuff .my-stuff-sprite, #your-stuff .your-stuff-sprite").click(function(e) {
// Prevent default click behavior
e.preventDefault();
// Get id of parent
var id = $(this).parent()[0].id;
// Execute function
actOnStuff(id);
});
});
});
Bad practice: Executing JavaScript within the href is a big no-no in todays environments. Even using onclick attributes et al is since long outdated.
Tip: Passing a function directly into jQuery is a shorthand for $(document).ready
Tip: Use console.log() instead of alert() to output everything from objects to strings to your log (might give you errors in older IE)
I still don't know where your placement element is located. Perhaps that's your culprit? If you have any questions about the above or anything else, don't hesitate to ask.
Also, check out jQuery Fundamentals which is a great resource for everyone using jQuery, from beginners to pros.
Edit: Check this jsFiddle for a demonstration of the above.
before
<script type="text/javascript" src="index.js"></script>
you should load jquery library first
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="index.js"></script>
Make sure you only have ONE element with id="placement", IE will fail if you have more than one.
Also what is the output of alert(strHTML); putted just before $('#placement').html(strHTML); does it output the string right?

Set onclick of <a> using JavaScript

I want to change all the links in a div such that they no longer refer to a page, but run a JavaScript function when being clicked. To do so, I wrote this function:
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
$div = $(htmlString).children("div#myDiv");
$div.children("a").each(function(i, element){toJavascriptLinks(element)});
document.getElementById("targetDiv").innerHTML = $div[0].innerHTML;
}
calling this function:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){console.log('Yeah!')};
console.log(element);
}
Now, when I run buildPageInDiv, 'string' is printed on the console, all the "href" are changed to "#" and for every <a> within the div the console prints the element:
<a href="#">
No sign of the onclick here, and clicking on the link does not show anything on the console.
What am I missing here?
Edit:
I was seeking in the wrong place. The problem was that I was running toJavascriptLinks(element) before attaching the innerHTML to targetDiv. That was no problem for the href attribute, but it was for the onclick attribute. Solution is simply to put it in targetDiv first and than run toJavascriptLinks(element) on targetDiv :
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
var content = $(htmlString).children("div#myDiv")[0].innerHTML;
document.getElementById("targetDiv").innerHTML = content;
$("div#targetDiv").children("a").each(function(i, element) toJavascriptLinks(element)});
}
Although the problem was not in the code I originally posted, the comprehensive answers below led me to the solution.
First: All type of selectors in jQuery, start with the dollar sign and parentheses: $()
Secondly: you need to close your statements with ;
Lastly: it is good practice to define your functions BEFORE you call them, instead of relying on javascript to hoist them to the top for you. This will also make jslint validate, whereas the other way round wouldn't!
So your code without your errors would look like:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){alert('Yeah!');};
console.log(element);
}
$('div').children("a").each(function(i, element){toJavascriptLinks(element);});
See this fiddle for a working demo.
Good Luck!!
ABOUT YOUR UPDATED QUESTION:
That's quite an update to your question.
You don't see your onclick in console.log because you set the onclick event in the dom. If you wanted to see the onclick in console.log, you would add the function STRING using:
element.setAttribute('onclick', 'your function string');
Suppose in your html you have:
<a id="link_a" href="http://www.google.com">link 1</a>
<a id="link_b" href="http://www.duckduckgo.com">link 2</a>
And you have this javascript:
var lnkA=document.getElementById("link_a");
var lnkB=document.getElementById("link_b");
lnkA.onclick=function(){alert(this.innerHTML);};
lnkB.setAttribute('onclick','alert(this.innerHTML);');
console.log(lnkA.outerHTML);
console.log(lnkB.outerHTML);
Then console.log will contain:
<a id="link_a" href="http://www.google.com">link 1</a>
<a onclick="alert(this.innerHTML);" id="link_b" href="http://www.duckduckgo.com">link 2</a>
See this fiddle for a live example of this explanation.
I also think you are already using some form of jQuery (without you knowing it) because of your use of .children("div#myDiv"). To my knowledge this no plain vanilla javascript. And I think both plain vanilla javascript and jQuery would not select those divs with id 'myDiv' out of a plain html-string, so the code in your update would not do the job.
Finally, to adjust my answer to your updated question and expectation of the onclick-event being visible in the parsed html-source:
var htmlString='<div id="myDiv">link 1link 2</div><div id="otherDiv">link 3link 4</div>';
function toJavascriptLinks(element){
element.href="#";
element.setAttribute('onclick','console.log("Yeah!");');
console.log(element.outerHTML);
}
//no innerHTML on documentFragment allowed, yet on it's children it's allowed
var frag = document.createDocumentFragment().appendChild( document.createElement('div') );
frag.innerHTML=htmlString;
var $div = $(frag).children('div#myDiv');
$($div).children("a").each(function(i, element){toJavascriptLinks(element);});
var outp=document.getElementById("output");
outp.innerHTML=frag.innerHTML;
See this updated fiddle to see it in action.
That leaves the question: why on earth are you placing 'ninja' $-signs front of your variable names?
That's just the way the debugger displays an HTML element. It doesn't show all attributes - especially since you are setting the DOM property onclick to a function reference, which can't be displayed as the HTML attribute onclick which takes a string (which AFAIK can't be set with JavaScript see Luc's comment).
Try console.log(element.onclick); instead, it should display something like function() {...}.
Or doesn't the event handle work?
BTW, any reason you don't use jQuery to set the href and the handler?
$div.children("a").attr('href', '#').click(function(){console.log('Yeah!')});
One more thing: In most consoles you can click on <a href="#"> and it will display the DOM properties, which should include the event handler.
I would really use jQuery for this, it's quite simple.
​$(function() {
$("div > a ").attr("href", "#").click(function(e) {
e.preventDefault();
doSomething();
});
});
var doSomething = function() {
alert("Woah, it works!");
}
See the following jsfiddle for it in action: http://jsfiddle.net/SsXtt/1/
Are you sure the element is correct? This works for me.
<a id="mylink">Test</a>
<script>
document.getElementById("mylink").onclick = function() {
alert("Works");
};
</script>
Function needs to be inside a string, try adding quotes?

Javascript: var is null

I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <head>
note: I am working with a local server, so pageload in instant.
function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
This here is the corresponding HTML
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
"changed is null:
changed.onchange = changeVisibility;"
i don't get it, I seriously don't get what I'm overlooking here.
EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code:
function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
This here is the corresponding HTML:
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
Also, thanks for the link to JSbin, didn't know about that, looks nifty.
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
note: I am working with a local server, so pageload in instant.
that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D
The onlything I'd like to do now is remove the Javascript link from the ...
Place an id on there, and inside your function do this:
document.getElementById('addField').onclick = addFileInput;
Or, as you already have the div as the variable 'a':
a.firstChild.onclick = addFileInput;
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.
I think its because you are trying to modify a file element.
Browsers don't usually let you do that. If you want to show or hide them, place them inside of a div and show or hide that.
Right, I've modified things based on your collective sudgestions and it works now. Onlything bothering me is the direct reference to Javascript inside the anchor
You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.
Placing at the bottom of the page works fine, as you can see here.
Decoupling event responder from your markup is covered under the topic of "Unobtrusive JavaScript" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.

Categories

Resources