Dynamically Written script not functioning - javascript

I have been bashing my head against a wall for about 4 hours now trying to figure out why this wont work. I have a program that needs to dynamically write code depending on the number of results from an SQL query.
I am using a jquery lightbox called EasyBox. When it is hard-coded like this, it works:
<body id="body" onload="bodyLoaded()">
<a id="link" href="#test" title="Snowflake" rel="lightbox">Hello</a>
<div id="test" style="display:none; width:320px; height:240px">
<p>Test Content</p>
</div>
<script type="text/javascript">
function bodyLoaded(){
$('#link').attr('onclick', 'logText("Hello")');
}
function logText(message){
console.log(message);
}
</script>
However, when I have the link written dynamically like this, the EasyBox popup does not fire.
<body id="body" onload="bodyLoaded()">
<div id="test" style="display:none; width:320px; height:240px">
<p>Test Content</p>
</div>
<script type="text/javascript">
function bodyLoaded(){
document.getElementById('body').innerHTML+="<a id='link' href='#test' rel='lightbox'>Hello</a>";
$('#link').attr('onclick', 'logText("Hello")');
}
function logText(message){
console.log(message);
}
</script>
Any ideas why this would work? I am pulling my hair out here!

I don't understand why you're not just using jQuery for all of this.
$(function(){
$('#body').prepend("<a id='link' href='#test' rel='lightbox'>Hello</a>");
$('#link').click(function(){
alert("Hello");
});
});
If the .click() doesn't work, you could also try .live(). Both worked for me in jsfiddle(http://jsfiddle.net/LZxrL/ and http://jsfiddle.net/LZxrL/1/).
Also, why does everyone keep saying there is no element with id='body' when the body element itself has the id of 'body.' Clearly, he wants to add a link to the body.
EDIT: I just read your comment on another post about the issue being the lightbox, not the click event. That DOES change things. I'm not familiar enough with that plugin to comment authoritatively, but I would suspect that the plugin looks for rel="lightbox" when the page loads and any elements added afterward won't be caught. Most plugins have a manual method, something like:
$('#link').lightbox();

I'm not seeing where you are loading the dynamic tags in your script. bodyLoaded() function is looking for anything with id='body' and in your second block of code I don't see any with that id tag.

Related

Trying to load HTML into a div with a button

I've spent enough hours googling this to feel comfortable posting this- even though i'm sure it's a simple solution. I'm just getting into a webdev so pardon my ignorance. As the title says i'm simply trying to have the content of an HTML file appear in a div after a button is pressed. Here is my code:
HTML:
<button id="button" class="linkGeneration">Press me</button>
<div id="renderArea" class="contentArea">
<!-- CONTENT SHOULD GENERATE HERE -->
</div>
Javascript:
$(document).ready(function() {
$('button').click(function(e) {
e.preventDefault();
$("#renderArea").load($(this).attr('../html/content.html'));
});
});
I'm not getting any errors, the button simply does nothing. I do have Jquery properly applied in my HTML as well.
Any suggestions on how to fix this OR a different method that might be simpler? Thanks.
The button doesn't have an attribute named ../html/content.html, so $(this).attr('../html/content.html') is not returning anything.
If you want to load from the URL, just use that as the argument to .load(), you don't need .attr().
$(document).ready(function() {
$('button').click(function(e) {
e.preventDefault();
$("#renderArea").load('../html/content.html');
});
});

How to .append text to a div using jQuery?

I'm trying to append a piece of text to a div using jQuery. I try to do this using the following code:
<html><head></head><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendButton").click(function(){
$("#conversation").append("<P>This is a message");
});
});
</script>
<div class="conversation"><p>some message</div>
<form><input type="button" id="sendButton" value="Send Message"></form>
</body></html>
Seeing the multitude of tutorials on the subject it seems to be such a simple thing to do, but I can't seem to figure out what I'm doing wrong here. Any help would be greatly appreciated.
You need to use class selector, As #conversation referes to element with id conversation
$(".conversation").append("<P>aergerag");
Fiddle DEMO
EDIT
You should look at this To Close or Not To Close Tags in HTML5 and a good question Closing tags in HTML5
replace # with . in your selector (conversation is a CLASS)
$(".conversation").append("<P>aergerag");
I am not any good at jQuery but from one of my projects I had to simply target the div with html as:
var someData = "This is a message";
$("#conversation").html(someData);
If some contents exists before this, then you can retrieve them, concatenate, and write it back into the target div.

My div show/ hide code works fine on a static HTML page but doesn't work on a Wordpress 3.5.1 page

This is sort of a condensed version of the code, the real version is too long to post but this is enough to represent the concept. I am using this to switch guitar diagrams based on several choices represented by anchors with the corresponding id in the href="". After spending several days getting it to work just right on a static html page, the script won't work in a Wordpress page which is where I intend to use it. I have tried it with the script in the head or inline (which shouldn't matter) - but either way it will not function. I know that Wordpress and certain plugins use Jquery so there may be a version mismatch causing conflicts. I am not (yet) an expert in javascript but I know there are several ways to skin a cat as the saying goes, I just need to find one that plays nice with Wordpress. Any help would be greatly appreciated...
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var divswitch = $('div.diagram_container a');
divswitch.bind('click',function(event){
var $anchor = $(this);
var ids = divswitch.each(function(){
$($(this).attr('href')).hide();
});
$($anchor.attr('href')).show();
event.preventDefault();
});
});
</script>
<style>
.diagram {
margin: 0;
width: 100%;
}
.diagram_container {
width: 100%;
}
</style>
<div id="RH_RW_Div" class="diagram_container" style="float:left; display:block;">
<div class="diagram_menu">
<a class="checked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="unchecked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/RH_RW.gif' /><br />
</div>
<div id="LH_RW_Div" class="diagram_container" style="float:left; display:none;">
<div class="diagram_menu">
<a class="unchecked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="checked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/LH_RW.gif' /><br />
</div>
Wordpress uses by default jQuery.noConflict(). This is to assure that there is no conflict by other libraries using the $ variable. That's why your console says it's not a function.
However, obviously, the jQuery variable still works, and you should use that, and passing to your function the $ variable yourself to enable the shorthand version of jQuery.
So your code should look like this:
jQuery(document).ready(function($){
// Your functions go here
});
My guess is that your Wordpress install or a plugin is already loading up jQuery in the head. Check to see if it exists there, and if it does, don't call it again.
If that doesn't do it and you have this site online, send me the link and I'll take a look.
Calling jQuery twice will often lead to problems. There is also a proper way to load jQuery and override the Wordpress version if you specifically need 1.8.3 (wp_register_script and wp_enqueue_script), but I don't think you need to go down that route yet.

Add button after script tag

I have a javascript that I want my users to be able to put on their sites. In this javascript, I want to generate a simple button, that is located exactly where the javascript has been pasted into the site. How can I do this? It would be simple if I could give my <script> tag an id and then just getting the element with the specific ID and appending after it, but I can't.
For example if I have something like this:
<body>
<p>test para</p>
<p>test para</p><p>test para</p><p>test para</p>
<p>test para</p>
<div>test div</div>
<script src="embed.js" type="text/javascript"></script>
<div>last div</div>
</body>
I want my button to be placed right between test div and last div (before or after the script tag, it doesn't matter). Can I do this?
Could you just use after -
$("div:contains('test div')").after('<input type="button"/>');
This would obviously be better if you could give the 'div' an id or a class rather than finding it by the text it contains.
jQuery can find a script tag using -
$("script[src='embed.js']").after('<input type="button"/>')
Demo - http://jsfiddle.net/7GPx7/1
embedding JavaScript something you may want to consider is your visitors may not have jQuery enabled on their sites, so you could bloat the call by loading jQuery or construct your requirement in pure JavaScript.
The embed snippet for your visitors
<script id="eduard_luca" src="http://cdn.example.com/embed.js" type="text/javascript"></script>
embed.js
var element = document.createElement('a');
element.setAttribute('href','http://google.com');
element.innerHTML = 'Click Me';
document.getElementById("eduard_luca").appendChild(element);
I Hope this help you with your project.

Can I assign an action from javascript dynamically?

Typically, I do this to prompt the alert box, and say Hello
<div style="color:#00FF00" onclick=alert("Hello"); id = "helloDivTag">
<h3>This is a header</h3>
<p>This is a paragraph.</p>
</div>
But this time, I don't want to do it inside the html tag, I want to do it inside the js. How can I do so? Thank you.
i would recommend using the jquery framework then you just do this
$(function(){
$('#helloDivTag').click(function(){
alert("Hello");
});
});
implementing it would look like this you just put it in the header
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$(function(){
$('#helloDivTag').click(function(){
alert("Hello");
});
});
</script>
why i recommend using jquery and not simple javascript is because there is alot of other functionality that could get in handy almost everytime you want to do something
window.onload = function() {
document.getElementById('helloDivTag').onclick = function(){
alert('hi');
}
}
when the window loads the click event is attached to your div and whenever you do the clicks the alert happens. This is called seperating behvaiour from structure and style.

Categories