Why wont my appendChild work? - javascript

I have a little javascript app set up here: http://jsfiddle.net/faYMH/
What i want it to do is add a
<div><h1>Hi there and greetings!</h1></div>
after
<div id='org_div1' onclick="addElement()">Hello</div>
using
<a href="#" onClick="addElement()" >add some</a>
(actually, what i want is for the onClick to go directly in the
So can anyone correct my code or provide some input?
(My next step is to also add a remove div, add an id to the new div with id + i++ )
Thanks so much!!

That's a quirk of JSFiddle. It wraps all of your code in a closure, so onclick handlers can't access your function. Either export the function into the global scope:
window.addElement=addElement;
Or change the little drop down in JSFiddle from "onLoad" to "no wrap (head)" or "no wrap (body)". While you're at it, you might want to change "Mootools" to "No-Library (pure JS)".

In your jsFiddle, addElement was scoped to inside the document ready handler and thus wasn't available to the click handler. I've modified the settings in the jsFiddle (without changing any code) to not have your code wrapped that way and it works for me now: http://jsfiddle.net/jfriend00/XVDYa/.
I changed the jsFiddle settings to "No-Library (pure JS)" and to "no wrap (head)". It's the second setting that really makes the difference here.

Related

JavaScript: backgroundImage isn't changing with onMouseOver

I'm pretty new to JavaScript, and I'm trying to figure something out. I have a series of images within a table, and I'd like each image to display within a div element when you hover over one. The problem is, the code doesn't appear to be doing anything. I hover over the div element, and no changes are being made to the #bigdisplay element. If I replace the backgroundImage with a property such as color, it works completely fine. What am I doing wrong? This is the code for my div element.
<div id="image1" onmouseover="document.getElementById('bigdisplay').style.backgroundImage='url('images/Slideshow1.png')';">
/* ... */
</div>
If I must provide any other code from my site I will (although I don't believe any of it is relevant). Any help would be greatly appreciated! Thank you!
Your code is fine. I separated the js just to make it easier to read. Your problem is either you have no height to the div or your path is wrong
function test(){ document.getElementById('bigdisplay').style.backgroundImage=
'url("https://res.cloudinary.com/rss81/image/upload/gw.jpg")'}
html,body,div{
height:100%;
}
<div id="bigdisplay" onmouseover="test()">
test
</div>
You're not properly escaping the string in the attribute. Attach the listener in Javascript instead, rather than in HTML attributes (which is as bad as eval) and it'll be easier to read and write:
const bigdisplay = document.querySelector('#bigdisplay');
document.querySelector('#image1').addEventListener('mouseover', () => {
bigdisplay.style.backgroundImage = "url('images/Slideshow1.png')";
});
I think one problem is that you used single quote to quote 'images/Slideshow1.png'. But you used single quote also for 'url('images/Slideshow1.png')'. So there is a conflict. Try 'url("images/Slideshow1.png")'. A part for this I find better to define the event handler function in the js document linked to the html document.

Why do I need 'javascript:' in the call to my javascript function?

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).
I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.
It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.
Here is a simplified version of the code used:
#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
cmCreateElementTag(1 + ", " + 2,"TagName");
}
HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
onclick="javascript: createTagging('parameter1', 'parameter2');"
title="atitle" aria-label="alabel">
<img id="ThumbNailImage_59244" src="https://image.jpg"
alt="" border="0"/>
</a>
-Troy
Why do I need 'javascript:' in the call to my javascript function?
You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.
In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.
Without the javascript: portion in the onclick, my function was not being called upon.
With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.
onclick attribute is always calling javascript in HTML.
onclick="createTagging('parameter1', 'parameter2');"
It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

Can you use a jQuery selector on a HTML tag that a JS string printed?

Sorry if the question was misleading, I couldn't find a better way to describe my problem. Anyway, here goes:
Suppose I had a button start that initially displays a string for me. Said string (let's call it stringA) is output through jQuery like this:
$(".start").click(function() {
$(".startButton").hide('slow', function() {
$("#table1").html(stringA);
});
});
Alright. Cool. That worked without a hitch. Now inside stringA I have multiple
<span class="optButton">this is a button</span> buttons. I have another onClick handler for my optButton button, and it goes like this:
$(".optButton").click(function() {
alert("Testing");
$("#table1").html(stringB);
});
Needless to say, clicking on optButton is supposed to replace the contents of #table1 with stringB. However, when I tried it, it doesn't work. I tried adding alert() to test and see if jQuery managed to select optButton, but it seems that it didn't because I get no popup from the alert() function.
My theory is that since optButton was not part of the original HTML and is within a string stringA, jQuery is unable to select optButton as a result. If this is true, is there a workaround to this issue? If it is not, what is the actual cause of the problem here?
You need to use event delegation since your span element has been dynamically added to the DOM:
$('#table1').on('click', '.optButton', function() {
alert("Testing");
$("#table1").html(stringB);
});
This technique will helps you to attach click handler to these newly created span elements.

Firefox add <a xmlns="http://www.w3.org/1999/xhtml">

EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.

Invoking Link in Javascript or jQuery

I have an href taged object (graphic) on a page that I want to programatically click on. However,I can't figure out how to reference the object. Here is the tag:
<div id="getthebutton">
<div>
<a onmouseout="MM_swapImage('btn123','','http://www.comp.com/img/btn_img.png',1)" onmousedown="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" onmouseover="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" href="javascript:do_activity("param1", 1);">
<img id="btn123" width="180" height="60" alt="" src="http://www.comp.com/img/buttons/other_btn.png"/>
</a>
</div>
</div>
How do I click on this thing? If I read this right "btn123" is just an image file.
To programmatically click on that you would have to do something like this
$("a").click();
Of course it helps to have an event handler assigned first, but it is really that simple :)
Using parentNode will give you access to the <a> tag, but I don't know if that helps you, cause I'm not sure what exactly you are doing.
document.getElementById("btn123").parentNode
I believe in jQuery, it is parent():
$('#btn123').parent()
So you could probably do:
$('#btn123').parent().click()
First off, you should really listen to the comments (javascript: links == dark side). That being said ...
$("div#getthebutton div a").click();
In this case, the anchor has a javascript href-value. Understanding that you have no control over the source, your only other option would be to evaluate the value of the HREF:
// run the href-javascript from the parent anchor
eval($("#btn123").parent().attr("href"));
Invoking a click from the code will not invoke the javascript code. As such, you must evaluate it instead.
If you want to get the result of clicking on the image, from the code I would say your JavaScript should simply be:
do_activity("param1", 1);
That's what ultimately happens when the image is clicked by a human. This bypasses the 'click' events, so you might miss out on some side-effects, but it's what I'd try first.

Categories

Resources