Make javascript if statement display html? - javascript

I wanted an if statement to show an image or html code depending on the webpage. I got this far and the html table doesn't appear at all (appears blank):
<script type="text/javascript">
<!--
var url = document.location.pathname;
if( document.location.pathname == '/tagged/photos' ){
document.innerHTML('<table><tr> hello </tr> </table>');
}
if( document.location.pathname == '/tagged/news' ){
document.write("<b>This is my news page</b>");
}
//-->
</script>

I'd do it slightly differently
Add both markup to the page, and show/hide as approproate:
<table id="table"><tr> hello </tr></table>
<span id="title"><b>This is my news page</b></span>
<script type="text/javascript">
$(function(){
var url = document.location.pathname;
if( url == '/tagged/photos' ){
$('#title').hide();
$('#table').show();
}
if( url == '/tagged/news' )
{
$('#title').show();
$('#table').hide();
}
})
</script>
I have assumed you have JQuery since it is tagged

You're using document.innerHTML, which doesn't exist. At the very least, you need to get a proper element:
document.documentElement.innerHTML = 'some HTML';
Setting aside everything else that's wrong with this approach, I'm not sure, why would you use document.write() in one branch and someElement.innerHTML in the other.

I'd suggest the following approach:
function pagePopulate() {
// you're looking at the pathname, use a sensible (meaningful) variable-name:
var pagePath = document.location.pathname,
// this is a map, of the relationship between page and content:
pathToContent = {
// pagename : html
'photos': '<table><tbody><tr><td>photos page</td></tr></tbody></table>',
'news': '<b>This is the news page</b>'
},
// getting a reference to the <body> element:
body = document.querySelector('body');
// setting the innerHTML of the <body>,
// if pagePath = 'tagged/photos', splitting with '/' would return:
// ['tagged','photos'], calling 'pop()' returns the last element of the array
// 'photos', which returns that string to the square brackets, resulting in:
// pathToContent['photos'], which would yield the '<table>...</table>' HTML.
// if that call resulted in an undefined, or falsey, value, then the default
// (the string *after* the '||' would be used instead:
body.innerHTML = pathToContent[pagePath.split('/').pop()] || '<h2>Something went wrong</h2><img src="http://blog.stackoverflow.com/wp-content/uploads/error-lolcat-problemz.jpg" />';
}
// calling the function:
pagePopulate();
References:
|| (logical 'or' operator).
Array.prototype.pop().
document.querySelector().
String.prototype.split().

Related

Jquery element with dot in tag name

Jquery when tag string contains dot. When hard coded, query get expected value, but if tag is obtained with a function and concatenated, query fails.
var tagWithDot = getTag(...) // tagWithDot === 'tag.withdot'
console.log(tagWithDot === 'tag.withdot') // true
console.log('#' + tagWithDot === '#tag.withdot') // true
console.log('#' + tagWithDot.replace('.', '\\.') === '#tag\\.withdot') // true
console.log($('#' + tagWithDot.replace('.', '\\.')) === $('#tag\\.withdot')) // false
console.log($(('#' + tagWithDot.replace('.', '\\.'))) === $('#tag\\.withdot')) // false
Instead of replacing manually . with \\. stuff you could use jQuery's escapeSelector
var tagWithDot = "#tag.withdot";
console.log( $.escapeSelector(tagWithDot) );
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
Using the replace('.','\\.') seems to work here.
Be aware though if you use $.escapeSelector you don't include the # or the # gets escaped too, and is likely not what you wanted.
var tagWithDot = "#tagwith.dot";
setTimeout(function () {
$(tagWithDot.replace('.','\\.')).text('Replaced');
}, 2000);
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
<div>Wait 2 seconds and replace text in div with id #tagwith.dot<div>
<br>
<div id="tagwith.dot">This should get replaced</div>

Change a string of two html files from javaScript

I have a list in one file html called "filed1":
<ul>
<li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br>
<FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>
Now I want to change a string in other html "filed2":
<a id="logo-header2">
<h1>
<span class="site-name" id="element">Details</span><br>
</h1>
</a>
Using Java Script:
function move() {
mywindow = window.open("file2.html");
mywindow.document.getElementById("element").innerHTML="Changed");
}
But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?
The problem is that you are trying to retrieve the DOM element before the window is loaded.
Try following
mywindow.onload = function() {
mywindow.document.getElementById("element").innerHTML="Changed";
}
Like #nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.
Another approach you can try is perhaps passing the string as a variable in the url, like so:
function move(){
window.open("file2.html?str=Changed");
}
And then in file2.html, try something that runs on page load:
window.onload = function(){
var str = $_GET('str');
document.getElementById("element").innerHTML = str;
};
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.

Using document.getElementById() inside a function

I have this code:
<div id="com_22">
<a onclick="delete(22);">delete entry</a>
</div>
and the javascript code:
function delete(url){
var tupu = document.getElementById("#com_"+url+"");
alert(tupu);
}
the problem is I'm having a null alert
I want to get the id
document.getElementById("#com_22");
How I can solve it
update
this is my code:
function confirmDel(url){
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '/files/assets/php/ajax/blog-stream.php?act=del',
data: 'url=' + url ,
success: function(h){
var status = h.status
if (status == "si" ) {
$("#com_"+url+"").fadeOut("slow");
}
}
});
});
}
the code excecutes so well except for the id didnt fade out
$("#com_"+url+"").fadeOut("slow"); <--- no working
See :: getElementById(), that should have been:
function delete_something(url){
var tupu = document.getElementById("com_"+url);
alert(tupu);
}
btw, try avoiding use of js pre-defined names as function name see:: delete
Don't include the hash when you're selecting by id. You're not using jQuery or querySelector.
var tupu = document.getElementById("com_"+url);
There is also no need to concatenate the empty string there at the end so I removed it.
Remove the '#' from within the bracket.
The function getElementById gets the element ID as a string, not a CSS-style selector. Change to:
var tupu = document.getElementById("com_"+url);
As can be extracted by javascript levels:
[{"file": ". m3u8" in this page: http: //ivm.antenaplay.ro/js/embed_aplay_fullshow.js? id = 6eI6sLVBfOL

With Javascript, how to read what is within <span> tags, when the value is created by Javascript

I have this code and I basically want it to read what is created in between the <span> tags (that value is created by another javascript script), and then take that to display 'article' or 'articles'.
<span id="quantity" class="simpleCart_quantity"></span>
<script type="text/javascript">
var q = document.getElementById('quantity');
if (q == 1) {
document.write("article");
}
else
{
document.write("articles");
}
</script>
So I want it to check <span id="quantity" class="simpleCart_quantity"></span>, and if the value that is present is '1', write 'article' and if the value is '0' or more than '1' write 'articles'. I hope you can get it.
Now it works, but only if you actually write something in between the <span>, like:
1
But the value is created externally and the script must be able to read the value that is created when the page is loaded right?
The result should be a sentence that says 'You have x article(s) in your shopping cart'.
I have no idea of how I should do this, I hope somebody can help me.
Thanks a lot!
<span id="quantity" class="simpleCart_quantity"></span>
<!-- ... --->
<span id="quantityText"></span>
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
</script>
Note that you must use a radix argument (10, in this case) to make sure numbers are interpreted as base10. Otherwise everything starting with '0x' would be interpreted as hexadecimal (base16), for example.
alternative syntax using the ternary operator:
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText"),
quantityValue = parseInt(quantity.innerHTML, 10);
quantityText.innerHTML = "article" + (quantityValue === 1 ? "" : "s");
</script>
In addition to pure javascript, you can also use jQuery:
jQuery($this).find('span.simpleCart_quantity') // find the span with class name: simpleCart_quantity
.text() // get the text

Replacing DIV content based on variable sent from another HTML file

I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>

Categories