I've got a basic HTML page, consisting of just:
<body id="body">
<script src="js/jquery-2.0.3.js" type="text/javascript"></script>
<script src="js/three.min.js" type="text/javascript"></script>
<script src="js/stats.min.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
</body>
as the main body of a index.html page, and where the content of application.js is:
function init() {
var container = $('div');
container.attr('id', 'container');
$('body').append(container);
alert('Container: ' + $('#container').length);
}
$(function() {
init();
});
So this is clearly some very basic code, I create a div and append it to the body. However, the alert call I make returns 0 and when I inspect the DOM tree via chrome, no div is added.
As I'm adding the script files to the bottom of the <body> tag, and calling init() from a jQuery ready() block, why would this be happening? Seems like such a basic and simple task.
Note: No errors are being thrown in chrome's console
Your line var container = $('div'); isn't creating a DIV, it's selecting one. If you want to create a container then do var container = $('<div></div>');
As a result, your current code returns an empty jQuery object, but you don't notice as jQuery plays nicely with them, and just does nothing.
$('div')
This selects all <div> elements in your page using an element selector.
You don't have any <div> elements, so it returns an empty jQuery object.
The rest of your code therefore has no effect.
It sounds like you actually want to create a new element:
$('<div />')
Related
SUMMARIZE THE PROBLEM
I state that I know practically nothing about html and javascript languages, I know the css. On wordpress, with visual composer, i was trying to make an entire row clickable. I've done it using a jQuery code founded online:
<script type="text/javascript">
jQuery(".LinkZoom1").click(function() {
window.location = "http://www.framedvision.org/portfolio/videomapping_oggetti_milano/";
});
</script>
I've added to the visual composer the object for java and I've put in the code. After I created the classes, inserted the link, added to the CSS the "cursor: pointer" function and everything works correctly.
THE PROBLEM IS THAT IT WORKS ONLY ON A SINGLE ROW. When I try to duplicate the code, assign different classes and links to create more clickable divs, it doesn't work. The result is that only the first div of the page is clickable, the divs are not.
WHAT I'VE TRIED
I tried the following codes in different combinations:
<script type="text/javascript">
jQuery(".class1”).click(function() {
window.location = “#1”;
});
</script>
<script type="text/javascript">
jQuery(".class2”).click(function() {
window.location = “#2”;
});
</script>
<script type="text/javascript">
jQuery(".class3”).click(function() {
window.location = “#3”;
});
</script>
<script type="text/javascript">
jQuery(".class4”).click(function() {
window.location = “#4”;
});
</script>
<script type="text/javascript">
jQuery(".class5”).click(function() {
window.location = “#5”;
});
</script>
Always using the object for java code: I put them all together, put individually in the row that I want to make clickable, it doesn't work. The result is always the same: only the first div becomes clickable. Even moving the object for java code away, from the first row to other rows, the result is the same. The first div is always the only clickable.
I found the solution. By importing the code written above, as corrected by you, it works. I don't know if this method is theorically correct, but it works fine. So...
In the visual composer, you have to insert an object to add the java code in each row that you want to make clickable (for example: for 5 clickable divs, you make 5 objects to insert the java code). Inside each object you have to insert the specific code for each class:
<script type="text/javascript">
jQuery(".class1”).click(function() {
window.location = “#1”;
});
</script>
So, I have following jquery function:
jQuery('.button').click(function(e) {
if(!isMobile) {
jQuery('.button').featherlight({
});
}
})
This creates an lightbox at the bottom of <body> like below:
Before lightbox is opened:
<body>
<button> Show lightbox</button>
<script src="https://...jquery.min.js"></script>
<script src="https://...custom_js.js"></script>
</body>
After lightbox is opened:
<body>
<button> Show lightbox</button>
<script src="https://...jquery.min.js"></script>
<script src="https://...custom_js.js"></script>
<div class="lightbox">Lightbox content</div>
</body>
Problem is that none of the jQuery function inside of this lightbox works as it was created after the page was loaded.
How do I "re-render" a js file after the lightbox is created?
Thanks!
Here is an example:
jQuery('#tags').keyup(function(e){
console.log(e);
if(e.which == 188) {
var tag = ...;
var data = '<button>tag</button>';
tags.push(tag);
jQuery('.tags ul').append(data);
jQuery(this).val('');
}
});
Here, a tag input will be "appended" or added to a div class="tags". However inside of the lightbox, this function is not executed at all.
Re-rendering a JS file is not how javascript is supposed to work.
What I recommend you to do is to run the a function in the afterContent callback.
As you can see in the featherlight documentation, there is a plenty of callbacks that can help you with this.
Example:
jQuery('.button').click(function(e) {
if(!isMobile) {
jQuery('.button').featherlight({
afterContent: function () {
// Do your code here
// The lightbox content will be ready
}
});
}
})
The proble here is that the light ox is dynamically added.
If you need any triggers to work inside or on that lightbox element you will need to use:
$(document).on('click', '.lightbox .button', function(){
...
});
Note that you do not want this code inside that lightbox, but inside your regular js file. Simply because we do not like inline js, and second you can trigger every dynamic content on the fly with above code.
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?
I am loading remote HTML into a DIV using jQuery and need to access all the elements and JS contained therein. Seems as though the inserted HTML is added and renders correctly but the elements are not in the DOM. How can I access these new elements ? Using document.getElementById('myDiv') returns null
var canvas .. in the script below returns null and I don't understand why.
<script>
function draw(){
var canvas=document.getElementById("pdf1");
var pdf=canvas.getContext("2d");
// other code here populates canvas.....
}
</script>
<body>
<div>
<canvas id="pdf1" width="801" height="1041"></canvas>
</div>
</body>
<script type="application/javascript">
$(window).load(draw());
</script>
</html>
$('#new_html_wrapper').load('file.html', function(){
// Access the new DOM elements here inside the load callback.
$(this).on('#myDiv','click',function(){
alert('You clicked on myDiv!');
});
$('#myDiv', this).css('background','red');
});
// Accessing the elements here will fail as they haven't been loaded yet.
Read more: http://api.jquery.com/load/
Also don't use document.getElementById('myDiv').
You already have jQuery loaded so do: $('#myDiv').
If you need to bind events to those new elements use the .on() function
You would have tried to get the content before HTML inserted there.
you should try accessing the element after content inserted. i.e. if you call the same function after content inserted, you can get the content in div.
or if you want to bind some events like click, on the content which comes later(inserted data like in your case) as well, you can live bind the events as below
$("div.className").live("click",function(){ alert('1'); })
or
$("document").on("div.className","click",function(){ alert('1'); })
I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.