Hihi. I'm trying to create an inline style sheet at the beginning of the page which reacts to what i'm GETTING from the url. Im doing this so I can have the navbutton of the page that im on highlighted. Kind of like here, www.myeg.net , but they have a static site and it is much easier.
<script type="text/javascript">
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var page=parseUrl('').search
function getSecondPart(str) {
return str.split('=')[1];
}
var site=getSecondPart(page);
var style = document.createElement("style");
style.innerHTML = ".nav_" + page + " { background-image:url('images/gradients/transparent_gradient.png');}";
document.body.appendChild(style);
}
</script>
</head>
<body>
<center><div><img width="960px" height="187.5" src="images/fullbanner.png"></div></center>
<div id="wrapper">
<div id="navbar">
<ul>
<li class="nav_index">Home</li>
<li class="nav_archive">News</li>
<li class="nav_squads">Roster</li>
<li class="nav_forum">Forums</li>
<li class="nav_about">Contact</li>
</ul>
I'm pretty noob at javascript so sorry ;;;
Try this:
<style type="text/css">
#banner{text-align:center;}
#banner>img{width:960px;height:187.5px;}
#nav>.selected{background-image:url('images/gradients/transparent_gradient.png');}
</style>
</head>
<body>
<div id="banner"><img src="images/fullbanner.png"></div>
<div id="wrapper">
<div id="navbar">
<ul id="nav">
<li id="nav_index">Home</li>
<li id="nav_archive">News</li>
<li id="nav_squads">Roster</li>
<li id="nav_forum">Forums</li>
<li id="nav_about">Contact</li>
</ul>
<script type="text/javascript">
document.getElementById('nav_'+window.location.href.split('=')[1]).className='selected';
</script>
You shouldn't use <center>, it's deprecated!
Instead of writing a style sheet with javascript in order to match an element, you should match a class and then only add that class to your element with javascript.
And I don't understand very well your code:
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var page=parseUrl('').search
It gives "" to me, but I have never seen .search on an anchor... If you want to get the current URL, you can do window.location.href.
And another point: if you use var outside functions (in global scope) you are creating a global variable, which won't be deleted and uses memory. Then, you can remove it when you don't want to use it anymore (var a="dagjhdjgailghkagh";/*code*/;a=null;), or use a self-execute function (closure) which contains your code.
Edit:
Sorry, instead of #nav>selected I meant #nav>.selected.
You can see a demo here: http://jsfiddle.net/VhWHp/
(But the url doesn't have =, so I replace it manually to 'archive'. In your site, remove that line)
And yes, it loads CSS first and then the nav. But that's the true power of CSS and javascript: if you set a class to an element after it has been loaded, that element will have the styles applied to that class.
Edit 2:
The problem is that if you do split('=')[1], the result will be something like "news&action" instead of "news".
Then, you could use a function I wrote some time ago:
function sQuery(arg) {
if(window.location.search){
var que = window.location.search.substring(1);
if(arg=='string'){return que;}
que = que.split("&");
if(!arg||arg=='array'){return que;}
for(var i=0;i<que.length;i++){
var qvar = que[i].split("=");
if(qvar[0]==arg){
return qvar[1];
}
}
}
return false;
}
Then, call the function like this: sQuery('site')
document.getElementById('nav_'+(sQuery('site')||'index')).className='selected';
You can also call sQuery('array') or just sQuery() if you want to get ["site=news","action=archive"], and sQuery('string') if you want "site=news&action=archive". If you won't use that, you can simplify the function:
function sQuery(arg) {
if(window.location.search){
var que = window.location.search.substring(1).split("&");
for(var i=0;i<que.length;i++){
var qvar = que[i].split("=");
if(qvar[0]==arg){
return qvar[1];
}
}
}
return false;
}
Related
I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click
I want to make a html which will auto get the information for a *.txt file
something1
something2
something3
and output into this html file
<!DOCTYPE html>
<html>
<head>
<title>List</title>
</head>
<body>
<ul>
#here to output#
</ul>
</body>
</html>
I prefer to use JavaScript. Some help is appreciated.
You have to request the file using AJAX call. Then you need to iterate through each line of response and generate DOM element (li in this case) and input line inside of it. After that insert each li element into your ul list.
You can achieve it using jQuery as you are probably new to JavaScript it's probably the easiest way.
What you need to do is request the file first:
$.ajax('url/to/your/file', {
success: fileRetrieved
});
Now after the file is retrieved jQuery will call fileRetrieved method, so we have to create it:
function fileRetrieved(contents) {
var lines = contents.split('\n');
for(var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
Now for each line from the file function fileRetrieved will call createListElement function passing line of text to it. Now we just need to generate the list element and inject it into DOM.
function createListElement(text) {
var into = $('ul');
var el = $('<li></li>').html(text);
el.appendTo(into);
}
Of course you don't want to retrieve into element each time createListElement is called so just store it somewhere outside the function, it's your call, I'm just giving you the general idea.
Here is an example of the script (without AJAX call of course as we can't simulate it):
var into = $('#result');
function fileRetrieved(contents) {
var lines = contents.split('\n');
for (var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
function createListElement(text) {
var el = $('<li></li>').html(text);
el.appendTo(into);
}
var text = $('#text').html();
fileRetrieved(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This element simulates file contents-->
<pre id="text">
fdsafdsafdsa
fdsafd
safdsaf
dsafdsaf
dsafdsafds
afdsa
</pre>
<div id="result"></div>
Try this
<html>
<head>
<title>List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="renderTxt_list">
</ul>
<input type="button" id="lesen" value="Read Data" />
</body>
<script>
$(document).ready(function(){
$("#lesen").click(function() {
$.ajax({
url : "testTxt.txt",
dataType: "text",
success : function (data) {
$html = "";
var lines = data.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
$html += '<li>'+lines[i]+'</li>';
}
$("body ul").append($html);
}
});
});
});
</script>
</html>
You need to request the file first, and then append it to your chosen place in the document.
You can for example use jQuery's get (or any other function like the native fetch), and then inject it into the ul element:
$.get("*.txt").then(x => $("ul").html("<li>" + x.split('\n').join('</li><li>') + "</li>"))
Let's break this solution by steps:
First, we need to request the external file:
$.get("*.txt")
Read about jQuery's get here. Basicly it will request the file you asked for using network request, and return a promise.
In the Promise's then, we can do stuff with the request's result after it is resolved. In our case we want to first break it by lines:
x.split('\n')
split will return an array that will look like this: ["line 1, "line 2", "line 3"].
JS arrays have the join method, which concat them to string while putting the string you want between the items. So after we do this:
x.split('\n').join('</li><li>')
We only need to add the <li> element to the start and end of the string like this:
"<li>" + x.split('\n').join('</li><li>') + "</li>"
Finally we appent it to your chosen element using jQuery's html.
Please, code to change domain in href (html, JavaScript).
Exemple:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
To:
<a id="NewL" href="http://exemple.net/indice.html">Indice</a>
Exemple code not working:
<script type = "text/javascript" >
function replace() {
var aEls = document.getElementById('NewL').getElementsByTagName('a');
aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>
Thanks, #t.niese:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Please help me, not change in various ID in same page:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Element.getElementsByTagName():
[...]The subtree underneath the specified element is searched, excluding the element itself.[...]
so you search for the elements with the tag name a within your element with the id NewL
Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a'), as of that you should only write:
var aEl = document.getElementById('NewL');
Also your replace is wrong, you don't need to escape the . if you pass the search as string.
aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');
Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.
change your javascript to the following:
<script type = "text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>
You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl
I have a string which contains this text:
<!DOCTYPE html>
<html>
<head>
<title>ExtractDiv test</title>
</head>
<body>
<p>Apples and oranges</p>
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
<p>Men and women</p>
</body>
</html>
Now I need a JavaScript function which gives me back a DOM element with a specific ID as a string from this text, for example:
function ExtractElementByIdFromString(HTMLString, IdString)
{
var ExtractedElement = ???(HTMLString, IdString);
return ExtractedElement;
}
So the RESULT of this function in this case would be:
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
Is this possible?
You can parse an HTML string with the native DOMParser:
var str = "<!DOCTYPE……………" // your HTML string
var doc = new DOMParser().parseFromString(str, "text/html")
Then just use regular DOM methods:
console.log( doc.getElementById("main") )
Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script> elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.
You can create a temporary element, put the HTMLString as a content to it, then use querySelector to get an element with passed id. Something like this:
function ExtractElementByIdFromString(HTMLString, IdString) {
var result,
temp = document.createElement('div'); // Create a temporary element
temp.innerHTML = HTMLString; // Set the passed string as HTML to the temporary element
result = temp.querySelector('#' + IdString).outerHTML; // Find an element with the passed id
return result;
}
A working demo at jsFiddle.
I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}