Class model for html backend [duplicate] - javascript

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.
The JavaScript I use for that is as follows:
var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");
function Inbox() {
inbox.style.visibility='visible';
}
function Friends() {
friends.style.visibility='visible';
}
function Agenda() {
agenda.style.visibility='visible';
}
function List() {
list.style.visibility='visible';
}
function News() {
news.style.visibility='visible';
}
function Notes() {
notes.style.visibility='visible';
}
The div elements are like this:
<div id="u-content-inbox" style="visibility:hidden;">
Inbox
</div>
<div id="u-content-friends" style="visibility:hidden;">
Friends
</div>
Each div has a "u-content-x".
However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null
I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?
Whenever I run a check on
if(!inbox) {
alert("Inbox div has not been found);
}
does not show the alert message.

Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.
<script src="some/path/to/file.js"></script>
</body>
If your scripts appear in the document before the elements do, you can put your code inside of this load event function:
window.addEventListener('load', function() {
//your code here
});
Just as a note on your code architecture, you could attach a class to each element and then do this:
var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
var elem = toMakeVisible[i];
elem.style.visibility = 'visible';
}

Related

Returned JavaScript value wont render inside a div element

This a basic question (Posting this again, as it was not re-opened after I updated the question). But I couldn't find any duplicates on SO.
This is a script I intend to use in my project on different pages. The purpose is to override the default ID shown in a span element to the order number from the URL parameter session_order. This doesn't affect anything and only enhances the UX for my project.
scripts.js (loaded in the header):
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
And in my HTML template, I call the function this way,
<div onload="this.innerHTML = get_url_parameter(window.location.href, 'session_order');">24</div>
Also tried this,
<div><script type="text/javascript">document.write(get_url_parameter(window.location.href, 'session_order'));</script></div>
When the page is rendered, nothing changes. No errors or warnings in the console either for the first case.
For the second case, console logged an error Uncaught ReferenceError: get_url_parameter is not defined, although script.js loads before the div element (without any errors).
Normally, I'd do this on the server-side with Flask, but I am trying out JavaScript (I am new to JavaScript) as it's merely a UX enhancement.
What am I missing?
Try this:
// This is commented because it can't be tested inside the stackoverflow editor
//const url = window.location.href;
const url = 'https://example.com?session_order=13';
function get_url_parameter(url, parameter) {
const u = new URL(url);
return u.searchParams.get(parameter);
}
window.onload = function() {
const el = document.getElementById('sessionOrder');
const val = get_url_parameter(url, 'session_order');
if (val) {
el.innerHTML = val;
}
}
<span id="sessionOrder">24</span>
Define the function you need for getting the URL param and then on the window load event, get the URL parameter and update the element.
Here you go. Try to stay away from inline scripts using document.write.
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
window.addEventListener('load', function() {
const url = 'https://yourpagesdomain.name/?session_order=hello'; //window.location.href;
const sessionOrder = get_url_parameter(url, 'session_order');
document.getElementById('sessionOrder').innerText = sessionOrder;
});
<div id="sessionOrder"></div>
The order of your markup and script matters...
<div></div>
<script>
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
</script>
<script>
document.querySelector('div').innerHTML = get_url_parameter('https://example.com?session_order=2', 'session_order');
</script>

Show LOADING in innerHTML while object is being loaded

I have following JavaScript function that load contents return by contacts.php into DIV id contacts-container, it takes a lot of time to complete the task. I want to show "LOADING.." text in the DIV id contacts-container while contents are being loaded.
function load_contacts() {
document.getElementById("contacts-container").innerHTML='<object type="text/html" data="contacts.php" ></object>';
}
I want solution in pure JavaScript.
What about some more JS?
function load_contacts() {
var el = document.createElement("object"),
target = document.getElementById("contacts-container")
target.innerHTML = "<span>Loading...</span>";
el.onload = function() {
target.firstChild.remove();
}
el.setAttribute("type","text/html");
el.setAttribute("data","contacts.php");
target.appendChild(el);
}
You can do with ajax. For this my suggestion, you must Jquery Ajax. For example,
$("#loadingElement").html("Loading");
$.load("#contacts-container",{},"contacts.php",function(){
$("#loadingElement").html("");
});

DOM Element reference is null - Uncaught TypeError: Cannot read property 'style' of null

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.
The JavaScript I use for that is as follows:
var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");
function Inbox() {
inbox.style.visibility='visible';
}
function Friends() {
friends.style.visibility='visible';
}
function Agenda() {
agenda.style.visibility='visible';
}
function List() {
list.style.visibility='visible';
}
function News() {
news.style.visibility='visible';
}
function Notes() {
notes.style.visibility='visible';
}
The div elements are like this:
<div id="u-content-inbox" style="visibility:hidden;">
Inbox
</div>
<div id="u-content-friends" style="visibility:hidden;">
Friends
</div>
Each div has a "u-content-x".
However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null
I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?
Whenever I run a check on
if(!inbox) {
alert("Inbox div has not been found);
}
does not show the alert message.
Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.
<script src="some/path/to/file.js"></script>
</body>
If your scripts appear in the document before the elements do, you can put your code inside of this load event function:
window.addEventListener('load', function() {
//your code here
});
Just as a note on your code architecture, you could attach a class to each element and then do this:
var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
var elem = toMakeVisible[i];
elem.style.visibility = 'visible';
}

Javascript: Return original innerHTML on mouseout

I am sorry for this very basic question. I am very new to javascript and learning it.
I am stuck with one easy problem-
This is what i am trying to do-
I have a header that has some innertext
<h1 id="bd" onmouseover="fun1()" onmouseout="fun2()"> sample</h1>
I am chaging innerHTML of this header on mouseover like this-
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
well on mouseout i do the same but for getting original innerHTML for this header tag.
function fun2()
{
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
}
But onmouseout function shows me changed innerHTML, that is a in this case.
How do i get original innerHTML sample again onmouseout?
I want this to be done in javascript.
I tried another way more
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
function fun3()
{
var ds=document.getElementById("bd").innerHTML;
alert(ds);
}
function fun2()
{
document.getElementById("bd").innerHTML=fun3();
}
but it is not working also.
A very generic version would be the following:
First change your markup a bit:
<h1 id="bd" onmouseover="fun1(this)" onmouseout="fun2(this)"> sample</h1>
This way you don't need to look up your element again in your callback function. This works then for more than one element you mouse over. Then you go:
function fun1(elm) {
if (!fun1.cache) fun1.cache = {}; // extend your function with a cache
fun1.cache[elm.id] = elm.innerHTML; // write into cache -> fun1.cache.bd
elm.innerHTML = 'a';
}
function fun2(elm) {
if (fun1.cache && fun1.cache[elm.id]) { // see if cache exists and...
elm.innerHTML = fun1.cache[elm.id]; // read from it
}
}
This way you build a caching system that doesn't need an extra global variable but stays closer to your function.
The next step would be to use only one function and send the new value as a parameter. Create something like a toggle function:
<h1 id="bd" onmouseover="fun(this, 'a')" onmouseout="fun(this)"> sample</h1>
and then your function:
function fun(elm, newValue) {
if (!fun.cache) fun.cache = {};
var value = newValue || fun.cache[elm.id]; // no newValue means recover old value
fun.cache[elm.id] = elm.innerHTML; // alway save the old value
elm.innerHTML = value;
}
If you need more explanations about this and creating Objects just leave a comment to this answer and I'll come back with more details...
Good luck!!
Store the first innerHtml in a global variable ,and use this variable to backup the first innerHtml.
var oldInner = '';
function fun1()
{
oldInner = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=oldInner;
}
You'll need to store the original value somehow:
var originalInnerHTML = "";
function fun1()
{
originalInnerHTML = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=originalInnerHTML
}
Currently you just get the existing innerHTML and set it as the new innerHTML - it's always going to be the same. So this line never changes anything:
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
once you have changed the innerhtml of an element, old data is gone
In order to get the old data you first need to have it store in some other place.
For ex : on mouseover you can first copy the original html to a hidden div, and upon mouseout you can again copy from the hidden div to the main div.
hope this helps.
A very easy implementation will be to have the two text you want to display in the div. so you have:
<h1 id="bd">
<span id='sample1'>sample1</span>
<span id='sample2' style='display: none'>a</span>
</h1>
var el = document.getElementById("bd");
el.onmouseover = function() {
document.getElementById("sample1").setAttribute("style", "display: none");
document.getElementById("sample2").setAttribute("style", "");
}
el.onmouseout = function() {
document.getElementById("sample2").setAttribute("style", "display: none");
document.getElementById("sample1").setAttribute("style", "");
}

My javascript popup shows for a split second if there's a cookie

I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
var flag = 0;
var dcmntCookie = document.cookie.split(';');
for(var i=0;i < dcmntCookie.length;i++) {
var ck = dcmntCookie[i];
while (ck.charAt(0)==' ') {
ck = ck.substring(1,ck.length);
}
if(ck) {
cparts = ck.split('=');
if (cparts[0] == name) flag=1;
}
}
if(flag) {
return true;
} else {
return false;
}
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
document.getElementById('google').style.display = "none";
document.getElementById('google').style.visibility = "hidden";
}
else createCookie(name,"cookie 4 the day",1);
}
</script>
<script type="text/javascript">
function closeThisDiv()
{
var openDiv = document.getElementById('google');
openDiv.style.display = 'none';
}
</script>
<body onLoad="checkCookie('MyCookie')"
If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}
Or, you should add a style element to the HTML itself:
<div id="google" style="display:none"></div>
As your code is currently written, it sounds like it is doing what it is supposed to. It waits for the entire document to be loaded (including images) and then it hides the element with id="google". That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:
<body>
other HTML here
<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>
</body>
This will at least not wait for all images to load before hiding it.
I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}
Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
}
else document.getElementById('google').style.display = "inline";
document.getElementById('google').style.visibility = "visibility";
createCookie(name,"cookie 4 the day",1);
In case anyone runs into this problem. Worked great for me.

Categories

Resources