improve code on updating content inside div - javascript

I learned that you can update a content inside div by using jQuery. I want to improve this code as the content is being change after it loads. I want it to be permanent regardless if it's loading or not.
Here's my code.
function changeContent () {
var myelement = document.getElementById("topbarlogin");
myelement.innerHTML= "HELLO";
}
window.onload = changeContent ;
This is my html code
<div class="signuplink" id="topbarlogin">Login</div>

Either call your function at the end of your body tag without window.load in script tag...
It will execute function() faster than the window.load
Stack Snippet
<body>
<div class="signuplink" id="topbarlogin">Login</div>
<script>
function changeContent() {
var myelement = document.getElementById("topbarlogin");
myelement.innerHTML = "HELLO";
}
changeContent();
</script>
</body>
...Or you can use DOMContentLoaded EventListener...it is equivalent to the $(document).ready() jQuery
function changeContent() {
var myelement = document.getElementById("topbarlogin");
myelement.innerHTML = "HELLO";
}
document.addEventListener("DOMContentLoaded", function(event) {
changeContent();
});
<div class="signuplink" id="topbarlogin">Login</div>

On DOM Ready use .html() to set HTML of div.
// This is you DOM Ready
$(function(){
// Set HTML using jQuery
$("#topbarlogin").html("HELLO");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="signuplink" id="topbarlogin">Login</div>

Please try this
$("#topbarlogin").html("Hello");

Related

somebody help me how to bind a function to a dom async

My first js file content:
(function(){
var html = '<div class="wrapper"><a class="test">111</a></div>'
var app = document.getElementById('app');
setTimeout(function(){
app.innerHTML = html;
},10)
})()
My secondjs file content:
var app = document.getElementById('app');
app.addEventListener('click',function(e){
console.log(e.target);
e.target.addEventListener('click',function(){
alert(111)
})
});
Dom:
<div id="app"></div>
The question is how can I bind a function with dom 'test' by javascript, without Event commissioned. My English is not very good, hope you can understand and help me resolve this problem.
An old-school solution is set onclick handler directly on your a tag.
(function(){
var html = '<div class="wrapper"><a onclick="testClicked(event)" class="test">111</a></div>'
var app = document.getElementById('app');
setTimeout(function(){
app.innerHTML = html;
},10)
})()
function testClicked(e){
alert(111);
}
<div id= 'app'></div>
Don't use setTimeout to fix asynchronous loading issues. HTML5 parsing is asynchronous, and timing of when the setTimeout callback is invoked can be unpredictable. The DomContentLoaded event allows you to execute code when the document is ready in the order you specify:
document.addEventListener("DOMContentLoaded", function(){
var html = '<div class="wrapper"><a class="test">111</a></div>'
var app = document.getElementById('app');
app.innerHTML = html;
});
Notice the anonymous function is not immediately invoked using an IIFE and is instead called as an event handler. Listeners added to the same node are executed in the order they were added. If the second script is always loaded synchronously after the first, you can add a second event listener in the second file to find the .test element and add a click handler to it:
document.addEventListener("DOMContentLoaded", function() {
var app = document.getElementById('app');
app.querySelector("a.test").addEventListener('click',function(e){
alert(111);
});
});
This approach is an example and assumes that the JavaScript file structure presented in the question is the most suitable for the app - there will always be other ways of doing the same thing.
Run this snippet for a demonstration (does not use external script files):
<script>
document.addEventListener("DOMContentLoaded", function(){
var html = '<div class="wrapper"><a class="test">111</a></div>'
var app = document.getElementById('app');
app.innerHTML = html;
});
</script>
<div id="app"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var app = document.getElementById('app');
app.querySelector("a.test").addEventListener('click',function(e){
alert(111);
});
});
</script>

Dynamic load of whole jstree

I have this working example of jstree properly initiated allowing to browse through tree structure and trigger action when user clicks the node: https://jsfiddle.net/8v4jc14s/.
When I try to load the tree dynamically it's not working:
<div id="container">
<button onclick="load()">Load tree</button>
</div>
<script>
$(function () {
$('#tree_div')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
});
function load() {
document.getElementById("container").innerHTML = "<div id=\"tree_div\"><ul><li id=\"Root\">Root<ul><li id=\"Sub\">Sub</li></ul></li></ul></div>";
}
</script>
Is there a way to "initiate" the tree after dynamic load?
You can copy but you cannot bind events to copied element since you have initialized only one instance of jstree.
If you want another jstree, you need to make another instance.
You can check this:
$(function () {
$('#tree_div')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
attach();
second();
});
//just copies UI
function attach(){
var $elem = $("#tree_div").clone(true, true);
$("#myTest").append($elem);
}
//for another instance
function second(){
$('#yourTest')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
}
https://jsfiddle.net/8v4jc14s/3/
During further research I have found this question: How do you execute a dynamically loaded JavaScript block?
I have used answer from Roman coming up with below code that looks to be working well.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="container">
<button onclick="load()">Load tree</button>
</div>
<script>
function load() {
// Clear container DIV to avoid adding tree div multiple times on multiple clicks
document.getElementById('container').innerHTML = "<button onclick=\"load()\">Load tree</button>";
// Creating new DIV element
var newdiv = document.createElement('div');
// Creating a jstree structure under newly created DIV
newdiv.innerHTML = "<div id=\"tree_div\"><ul><li id=\"Root\">Root<ul><li id=\"Sub\">Sub</li></ul></li></ul></div>";
// Creating new SCRIPT element
var script = document.createElement('script');
// Creating SCRIPT element content
script.innerHTML = "$(function () {$('#tree_div').jstree().on('changed.jstree', function (e, data) {alert(data.selected);});});";
// Adding SCRIPT element to newly created DIV
newdiv.appendChild(script);
// Finally updating "container" DIV
document.getElementById('container').appendChild(newdiv);
}
</script>
Hope this helps others like me lost in mysteries of JS :)

Function out of scope?

I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction from button onclick in html:
<button onclick="myFunction();"></button>
But it says myFunction is not defined. I understand because this is inside window.onload. How can I fix this? I need window.onload because I need to use document.getElementById("testID") to get content.
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload. You simply have to put the code somewhere after the element with ID testID in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this or event.target:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
You defined it within a function so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}

jQuery + Module Pattern: When to declare/query elements?

Typically, you don't start querying the DOM until the $(document).ready().
In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
Would it be better to put this whole Widget definition inside the $(document).ready()?
Should I wait until the Widget.init() to query the elements?
Note: I'm brand new to JS design patterns, so please note if I'm missing something
Option1
Widget = {
ele : $('#ele'),
init : function(){ ... }
};
$(document).ready(function(){
Widget.init();
});
Option2
Widget = (function(){
var privateEle = $('#privateEle');
return {
publicEle: $('#publicEle'),
init: function(){ ... }
};
}());
$(document).ready(function(){
Widget.init();
});
What I would do:
var Widget = (function(){
var ele;
function init(_ele){
ele = _ele;
};
return {
init: init
};
})();
$(function(){
Widget.init( $('#foo') );
});
If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []
EDIT: btw.. put your <script> tags before </body> NOT within <head></head>
It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.
what would work though is on of the following:
create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.
Widget = {
ele : $("<div id='ele'>"),
....
}
or you can query the element on widget initialization.
Widget = {
ele : "#ele",
init : function(){
this.ele = $(this.ele);
...
}
}
You can include script just before body end tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<!-- my HTML -->
<script src="../js/vendor/jquery-1.9.1.js"></script>
<script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
<script src="../js/custom.js"></script>
</body>
</html>
DOM is ready (no need for $(document).ready):
/*custom.js */
var Widget = (function($){
var _$element;
return {
init: function(){
_$element = $('#myElementId');
// TODO - element is available from now on
};
};
}(jQuery));
Widget.init();

prettyphoto wont load when writing href using document.write

i have some codes like this
<span id="$RsC" class="menu" title="Action menu" onclick="menu(\''.$RsC.'\')">click</span>
function menu(id){
var d = document.getElementById(id);
d.innerHTML ='<a href="somthing;iframe=true&width=400&height=170" rel="prettyPhoto[iframe]" >Doesnt work</a>';
}
<script type="text/javascript" charset="utf-8">
jQuery.noConflict();
jQuery(document).ready(function($) {
$(".pp_pic_holder").remove();
$(".pp_overlay").remove();
$(".ppt").remove();
$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'h0mayun'});
});
</script>
the problem is that after clicking on "click" and writing html link prettyPhoto plugin doesn't load
any help will be appreciated.
EDIT-------------------
damn you conflict it was again jquery conflict but to got it work i change function to this:
<script type="text/javascript" charset="utf-8">
jQuery.noConflict();
jQuery(document).ready(function($) {
$(".pp_pic_holder").remove();
$(".pp_overlay").remove();
$(".ppt").remove();
$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'h0mayun'});
});
</script>
function menu(id){
var d = document.getElementById(id);
d.innerHTML ='<a href="somthing;iframe=true&width=400&height=170" rel="prettyPhoto[iframe]" >Doesnt work</a>';
jQuery.noConflict();
jQuery(document).ready(function($) {
$(".pp_pic_holder").remove();
$(".pp_overlay").remove();
$(".ppt").remove();
$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'h0mayun'});
});
}
And it is not going to work this way. You initialize prettyPhoto for existing elements on the page after your page was loaded. When you insert a new element, prettyPhoto plugin knows nothing about it, because it already "attached" itself to the elements existed before. You have to initialize prettyPhoto after all changes on the page or attach it after changes to the updated elements. Like this
function menu(id){
var d = document.getElementById(id);
d.innerHTML ='<a href="somthing;iframe=true&width=400&height=170" rel="prettyPhoto[iframe]" >Doesnt work</a>';
$('a', d).prettyPhoto({theme:'h0mayun'});
}
ps: I've made a simple test with the example of prettyPhoto and it is working
function menu(id){
var d = document.getElementById(id);
d.innerHTML ='Test link';
$('a', d).prettyPhoto();
}
If you're doing this $(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'h0mayun'}); before the onClick function.
You would have to do it again after you have written the html of the object so the plugin would initialize again.

Categories

Resources