I have a project that consists of multiple visualizations, all using the same dropdown menu for selecting what csv to load. I want to be able to add new options once and have it changed on all the files. Best way is to use html and javascript code in one file, and have it included on the others, so that if I want to add more options in the dropdown menu I only do it in that single file. Is there a way to do this with html, and if so, do I have to change the layout of the reusable "A" file so that it is properly used inside the rest? If it cannot happen with html, what is the best way to do it and what changes to I have to make in the code layout in the documents?Here is the reusable code that has to be on file A:
<div id="dropdown">
<select id = "opts">
<option value = "ds1">Atlas</option>
<option value = "ds2">BioSQL</option>
<option value = "ds3">Coppermine</option>
<option value = "ds4">Ensembl</option>
<option value = "ds5">Mediawiki</option>
<option value = "ds6">Opencart</option>
<option value = "ds7">PhpBB</option>
<option value = "ds8">Typo3</option>
</select>
</div>
<script type="text/javascript">
var ds1="../CSV/atlas/results/metrics.csv";
var ds2="../CSV/biosql/results/metrics.csv";
var ds3="../CSV/coppermine/results/metrics.csv";
var ds4="../CSV/ensembl/results/metrics.csv";
var ds5="../CSV/mediawiki/results/metrics.csv";
var ds6="../CSV/opencart/results/metrics.csv";
var ds7="../CSV/phpbb/results/metrics.csv";
var ds8="../CSV/typo3/results/metrics.csv";
</script>
And I want to include this after the style block in files B,C,D etc that look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="../d3/d3.js"></script>
<script type="text/javascript" src="../d3/d3-tip.js"></script>
<style type="text/css">
body{
font: 16px Calibri;
}
</style>
<!--...HERE IS WHERE I WANT TO INSERT THE CODE FROM THE A FILE-->
</head>
<body>
<script type="text/javascript">
I have seen other posts asking somewhat the same thing, but haven't found a way to do this. I think it has to do mostly with the fact that I insert both html and javascript code, but I'm generally new to this and cannot figure the proper way. Thanks in advance for any help.
Let's assume you store what you call file A in options.html, then my suggestion is the following:
"script.js":
// because you put your script in the <head> of B,C,D we wait for the page to load
window.onload = function () {
// We locate the dropdown menu
var dropdownMenu = document.getElementById('dropdown');
// load the file via XHR
loadHTML(function (response) {
// the response will be a string so we parse it into a DOM node
var parser = new DOMParser()
var doc = parser.parseFromString(response, "text/html");
dropdownMenu.innerHTML = doc.getElementById('dropdown').innerHTML;
// in case you want to do something with the references to the .csv files
var csvFiles = doc.getElementsByTagName('script')[0];
console.log(csvFiles);
})
};
function loadHTML(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("text/html");
xobj.open('GET', 'options.html', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
Note that this only runs, if you host it on a http-Server. In other words it won't run locally due to Same-origin policy.
Parsing string to DOM was inspired by this answer.
loading the HTML file via XHR was inspired by this post on codepen.
I modified your version of B,C,D:
reference to script.js in the head-Element
added a div-Element with ID "dropdown"
That's done with php just call it like this:
<?php include('file.html'); ?>
Related
Im still new to javascript and ajax and all that. Im working on a project for my web dev course and have been stuck on this for a while now. The professor hasnt been of any help.
I am making a data page. On the index there are 4 radio buttons, each on loading another html page into the div. Each of these other pages have data sets and allow for searches on a few of the fields. The issue is that when these pages are called by the index page, none of the functions work on them anymore. The functions work on them when I open the page alone and not through the index.
This is the Index Page html and javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
<link href="index.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<h1> Welcome to Data Sets - Calgary</h1>
<table id="buttons">
<tr><td>Find Calgary Libraries</td><td>Find Traffic Incidents In Calgary</td><td>Search Calgary Building Permits</td><td>Search Calgary Crimes</td></tr>
<tr><td><p>Clicking on this loads a search for Calgary Libraries</p></td><td><p>Clicking on this loads a search for Calgary traffic incidents</p></td><td><p>Clicking on this loads a search for Calgary Building permits</p></td><td><p>Clicking on this loads a search for Calgary Crimes</p></td></tr>
<tr><td><input type="radio" id="calgLib" name="butt"></td><td><input type="radio" id="calgTraff" name="butt"></td><td><input type="radio" id="calgBuild" name="butt"></td><td><input type="radio" id="calgCrime" name="butt"></td></tr>
</table>
<div class="buttonresults" id="buttonresults">
</div>
</body>
</html>
window.onload=registerListeners;
function registerListeners() { var asd; asd=document.getElementById("calgLib"); asd.addEventListener("change", function () { getContent("liblocations.html");}, false); asd=document.getElementById("calgTraff"); asd.addEventListener("change", function () { getContent("trafficincident.html");}, false); asd=document.getElementById("calgBuild"); asd.addEventListener("change", function () { getContent("buildpermit.html");}, false); asd=document.getElementById("calgCrime"); asd.addEventListener("change", function () { getContent("commcrime.html");}, false); }
function getContent(infopage) {
asynchrequest= new XMLHttpRequest();
asynchrequest.onreadystatechange = function() {
if (asynchrequest.readyState == 4 && asynchrequest.status == 200) { document.getElementById("buttonresults").innerHTML = asynchrequest.responseText; } }; asynchrequest.open("GET", infopage, true); asynchrequest.send(); }
This is one of the pages being called from the index
<script src="liblocations.js"></script>
<h1>Find Calgary Libraries</h1>
<div class="textfields">
<table id="fields">
<tr><td><label>Find Libraries by Name </label></td><td><input type="text" id="libname"></td></tr>
<tr><td><label>Find Libraries by Postal Code </label></td><td><input type="text" id="libPostal"></td></tr>
<tr><td><label>Find Libraries by Square Feet </label></td><td><input type="text" id="libSquareFeet"></td></tr>
</table>
</div>
<br>
<br>
<h3 id="searchvalue"> Enter a search</h3>
<table id="searchresults">
</table>
This is the unfinished Java script for the liblocations page
var xhr = new XMLHttpRequest; var parsedrecord; window.onload=pageSetup;
function pageSetup() {
document.getElementById("libname").addEventListener("keyup", function (){ searchByLibraryName();},false);
document.getElementById("libPostal").addEventListener("keyup", function (){ searchByLibraryPostal();},false);
document.getElementById("libSquareFeet").addEventListener("keyup", function (){ searchByLibrarySqrFeet();},false);
xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { parsedrecord = JSON.parse(xhr.responseText); } }; xhr.open("GET", "https://data.calgary.ca/resource/m9y7-ui7j.json", true); xhr.send();
}
function searchByLibraryName() { document.getElementById("searchvalue").innerHTML="Searching by Library Name"; var librarytoUse=libname.value.toUpperCase(); libPostal.value=""; libSquareFeet.value=""; var gmap=""; var position=""; var output="<tr><th>Library</th><th>Postal Code</th><th>Square Feet</th><th>Phone Number</th><th>Location</th></tr>";
for(var i=0;i<parsedrecord.length;i++)
{
var record=parsedrecord[i];
var searchLib=record.library.toUpperCase();//assign
if(searchLib.startsWith(librarytoUse))//partial match on string
{
output+="<tr><td>";
output+=record.library;
output+="</td><td>"
output+=record.postal_code;
output+="</td><td>";
output+=record.square_feet;
output+="</td><td>";
output+=record.phone_number;
output+="</td><td>";
position=record.location.latitude+","+record.location.longitude;
gmap ="<a href=https://www.google.com/maps/search/?api=1&query="+position+" target=_blank>Click here to see map</a> ";
output+=gmap;
output+="</td></tr>";
}
}
document.getElementById("searchresults").innerHTML=output;
}
When opening liblocations.html, the functions work but when I use the radio button and the index.html
loads the page, the functions stop working. I'm not sure what is going on, or how to fix it. Any help is appreciated!
This is the index page calling the liblocations
enter image description here
This is what the liblocations page looks like when I open it alone
enter image description here
In the index.html page put this line <script src="index.js"></script> end of the body tag . I mean here:
<script src="index.js"></script>
</body>
From personal experience, things can quickly get messy when using XMLHttpRequest for fetching data in JavaScript. A much better option would be to use the Fetch API, which you can read more about on the MDN Web Docs. I'm not sure if this is the exact problem you're facing, but I do know that trying to run asynchronous code with XMLHttpRequest (rather than async/await and the Fetch API) can cause many unintended consequences that can be confusing unless you really know what you're doing. That is unless you have a valid reason for using XMLHttpRequest, such as having to target IE.
Goal: The purpose is that a sheet will contain information, this information is placed inside a namedrange, the namedrange will be dynamic (the entire column is given a namedrange).
I created a html popup which contains a dropdown list. This dropdown list must contain the list of information from the namedrange.
I am unable to understand how this is to be done. Here is the code below:
function fncOpenMyDialog() {
var htmlDlg = HtmlService.createHtmlOutputFromFile('HTML_myHtml')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'New File');
};
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var ui = SpreadsheetApp.getUi();
ui.createMenu('New')
.addItem('New Save File Extension','fncOpenMyDialog')
.addToUi();
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select name="nameYouWant" placeholde="File Type">
<option value="something">Word</option>
<option value="anything">MS Excel</option>
<option value="anything">MS Powerpoint</option>
<option value="anything">MS Slides</option>
</select>
<hr/>
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
As you can see in my html file, that the extensions are currently hardcoded.
I am trying to make this dynamic, how do I achieve this?
I believe your goal as follows.
You want to put the values to the dropdown list by retrieving from the named range of the Spreadsheet.
In this case, is the named range the same with this thread?
For this, how about this answer?
Modification points:
From google.script.host.close(), I understood that the HTML file of HTML_myHtml is included in the Google Apps Script project. By this, I would like to propose to achieve your goal using google.script.run.
If the named range is the same with your previous question, you can use it by modifying a little.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML and JavaScript side: HTML_myHtml
Please modify HTML_myHtml as follows.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="select" name="nameYouWant" placeholde="File Type"></select>
<hr />
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
google.script.run.withSuccessHandler(v => {
const obj = document.getElementById("select");
v.forEach(e => {
const option = document.createElement("option");
option.text = e;
option.value = e;
obj.appendChild(option);
});
}).readNamedRange();
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
Google Apps Script side: Code.gs
At above HTML, readNamedRange() is used. So please put the following script. If you have the same function names, please modify them. In this script, the values are retrieved from the named range of listDown, and sent to HTML side using google.script.run.
function readNamedRange() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var result = activeSheet.getRange("listDown").getValues();
var end = activeSheet.getLastRow();
var values = [];
for (var i = 0; i < end; i++) {
if (result[i][0] != "") {
values.push(result[i][0]);
}
}
return values;
}
Note:
About window.saveDia = function() {onOpen()};, unfortunately, I couldn't understand about what you want to do.
Reference:
Class google.script.run
I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>
I want to create a simple script that changes LESS variables and print the CSS output in a div.
this is my HTML
<input type="text" id="choose-color" onchange="ModifyColorsInLess()">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
This is my js
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status === 200 && xmlhttp.readyState === 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","css/styles.less",true);
xmlhttp.send();
}
function ModifyColorsInLess() {
less.modifyVars(
{
'#colore-body': $("#choose-color").val()
}
);
}
The script prints CSS code correctly, but if i insert a new color value in the input type="text" and call the writeCSS function, it doesn't print my variable edit.
I think the problem is that "modifyvar" does not change the file "styles.less", so when I call the function writeCSS() does not detect changes made.
is there a way to print the css dynamically detecting changes made with modifyvar?
update
When you allow the compiled styles are directly applied on your page, you can simply call `modifyVars as follows:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<link rel="stylesheet/less" type="text/css" href="t.less">
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
less.modifyVars({
'colore-body': document.getElementById('choose-color').value
});
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
Demo: http://plnkr.co/14MIt4gGCrMyXjgwCsoc
end update
Based on How to show the compiled css from a .less file in the browser?, How to update variables in .less file dynamically using AngularJS and Less: Passing option when using programmatically (via API) (you should also read: http://lesscss.org/usage/#programmatic-usage) you should be able to use the code like that shown below:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var options = {}
options['modifyVars'] = {'colore-body' : document.getElementById('choose-color').value}
lessCode = xmlhttp.responseText;
less.render(lessCode, options, function (error, output) {
if(!error) {
document.getElementById('lesscode').innerHTML = output.css;
}
else document.getElementById('lesscode').innerHTML = '<span style="color:red">' + error + '</span>';
});
}
};
xmlhttp.open("GET","styles.less",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
demo: http://plnkr.co/YbdtOwOeQPC1k9Vq4ZBv
And finally based on Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload you can prevent caching of your source file with the following code:
xmlhttp.open("GET","t.less?_=" + new Date().getTime(),true);
In the above the env: "development" setting prevents your source files from caching. To clear the cache otherwise, you should call less.refresh(true) before your less.render call.
i have another little problem, if in my less file there is a reference
to another less file like this(#import "another.less") script doesn't
work.
Make sure that another.less in the above is in the same folder as your styles.less file. Notice that import (when using less in browser) are read with a XMLHttpRequest too. So your imported files should be readable by browser and their paths should be relative to the styles.less file. Also see http://lesscss.org/usage/#using-less-in-the-browser-relativeurls
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);
}