I want to make an javascript file (attached to some website), which generates available stylesheets and while clicked on one's name changes the current stylesheet for the chosen one. I do it like that:
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = document.getElementsByTagName("link").item(i).href //getting name
//and here is my problem - I'd like to change that HTML code to js code, so that it generates a link wchich should change the style. I can't figure it out how to change that to js.
STYLE 3
}
//Here is the function that changes stylesheet (not mine, but working)
function changeCSS(cssFile, cssLinkIndex)
{
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link")
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
Can you please verify my code and help me with changing HTML code with link, to js code?
//Edit
I'm sorry but it's still not working... The website on wchich i'm using the code has 3 stylesheet, but i get no result.
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = new String(document.getElementsByTagName("link").item(i).href));
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
a.onclick = function(){ changeCSS(style,0)}; // When you click it, you call changeCSS
document.body.appendChild(a); // Append it to the body
}
I used your code, like above.
Inside your loop:
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
// When you click it, you call changeCSS
a.onclick = function(){ changeCSS(style,0)};
document.body.appendChild(a); // Append it to the body
If you want to append it to another element, change
document.body.appendChild(a);
To
whatEverElement.appendChild(a);
Some remarks:
appendChild adds an element as a child of another element, just like in changeCSS
I set both textContent and innerText to support old IE, if you don't need to, change to the textContent alone.
This code is assumed to be in the for loop.
Depending on what style is, there might be a closure trap here, if you see a problem with all elements getting the same style, that's what you got, and you need to wrap the code in another IIFE.
Here is a working example
Note it doesn't use change CSS, but alert because I don't know how to load external sheets in JSFiddle.
Related
var cssId = '../../../css/export-csv.css';
if (!document.getElementById(cssId))
{
var div = document.getElementsByTagName('div')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
div.appendChild(link);
}
I want to import a CSS file named 'export-csv.css' in my js file but I am not able to do that. Thanks in advance
href is used to reference the id and move the link from one place to another where its not assign. If you want to assign any value make it as "ID or class" then it will easy for you to call in javascript.
Try document.getElementsByTagName( "head" )[0].appendChild( link ); instead of
var div = document.getElementsByTagName('div')[0];
div.appendChild(link);
and check that css file path is correct , it should resolve the issue. More details at How to load up CSS files using Javascript?
function loadCSS(filename){
var file = document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", filename);
document.head.appendChild(file);
}
//just call a function to load a new CSS:
loadCSS("path_to_css/file.css");
So the following code should do the trick:
var aCSS=document.createElement('link');
aCSS.setAttribute('rel', 'stylesheet');
aCSS.setAttribute('type', 'text/css');
aCSS.setAttribute('href', 'someCssName');
document.getElementsByTagName('head')[0].appendChild(aCSS);
You can also load it in a blocking way by using document.write. The issue with loading CSS dynamically is that it degrades the user experience a lot, as the user will see a flickering of things at best case, and two different stories of the same element at worst case (slow css loading). I am not sure what is the use case, but please be careful when loading CSS dynamically.
I would suggest you using gulp or grunt to combine your css into one minified file and this would be a better approach IMO.
A few pieces are wrong here.
Your cssId looks like a file path. It could conceivably be an id but I doubt it.
There is no href. Since you are using an external stylesheet (<link> tag), your code needs to give the stylesheet an href, otherwise the browser will have no idea where to go fetch the styles from.
Inserting a stylesheet into a div is strange. It is more appropriate to put them in the head. While HTML5 does allow you to be a rebel, there are far more downsides than upsides to breaking this rule.
Here is a fixed example:
var cssId = 'some-legitimate-id';
if (!document.getElementById(cssId))
{
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
link.href = '../../../css/export-csv.css';
document.head.appendChild(link);
}
Try this:
var div = document.createElement("div");
In place of:
var div = document.getElementsByTagName('div')[0];
Might be unable to find the div[0].
Hi I am adding a iframe dynamically, It displays an image from a server. I need to disable the context menu for this item. In chrome I can inspect element and if I add oncontextmenu="return false" I do get the wanted affect. However I am unable to do this while the page is generated. Here is an example of the working html.
However I can not reproduce this when i frame is being created. Here is my code.
$(window).scrollTop(0);
$('#secVerify').show();
$("#popWaitLoad").modal("hide");
imgLoading.hide();
dvIframe.empty();
//else load deposit data into interface
$("#spanType").text(deposit.DepositType);
$("#spanReference").text(deposit.Reference);
$("#spanAmount").text("R " + deposit.Amount.toFixed(2));
$("#spanDate").text(deposit.DateCreatedOffsetS);
imageID = deposit.Deposit_Doc_imageID;
var url = imageUrl + '/' + deposit.Deposit_Doc_imageID + '/false';
var imgFrame = document.createElement("iframe");
imgFrame.src = url;
imgFrame.frameBorder = '0';
imgFrame.scrolling = 'no';
imgFrame.width = '100%';
imgFrame.height = '100%';
imgFrame.align = 'middle';
imgFrame.id = "iframeImg";
dvIframe.append(imgFrame);
I have tried examples like.
$("#iframeImage").contents().find("img").attr("oncontextmenu", 'return false');
$('#iframeImage img').on('contextmenu', function (e) {
e.stopPropagation();
// Your code.
return false;
});
But because the img element seems to be only created is done after page load it seems to not work. I know disabling the the menu will not help much and I have explained all the other methods of obtaining the image that is still available but the client really wants this.
I have added nocontextmenu to the body tag and it works everywhere except for the iframe.
So let me clarify, My iframe is working like it should however I would like to disable the right click aka context menu on the specific iframe.
I have used setAttribute to set the attributes and targeted a container to appendChild.
function example(){
var target = document.getElementById('container');
var element = document.createElement('img');
element.setAttribute('src', 'http://gopalshenoy.files.wordpress.com/2011/04/product_demos.jpg');
//element.setAttribute('width','100%');
//element.setAttribute('height','100%');
element.setAttribute('id','iframeImage');
element.setAttribute("oncontextmenu","return false;");
target.appendChild(element);
}
// Demo-Snippet use.
window.onload=example;
<!-- Demo Snippet use -->
<div id="container"></div>
If you build more than one element using this function you might find further issues due to duplicated ID's.
ID's are used to target a specific element 'one of' so if you want to build multiple elements I would recommend giving them unique ID's.
I hope this helps. Happy coding!
I want to download a file which is created from DOM element. So a user clicks a button on web page and it invokes a javascript method which may grab the contents of DOM element and prompt user for download.
I am able to grab contents of the DOM element inside a Javascript Var. But not sure how to proceed further.
For grabbing the DOM element i am using:
var elem = document.getElementById("userDownload");
I am not sure if I understand correctly what is the content that you are trying to download. If you have the content (which sounds like the HTML of an element?) stored in a variable, you can try:
("#downloadbutton").click(function() {
//var content = content of file;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
dl.click();
});
I appreciated finding this question, but at least on Firefox running with linux, you need to append the dl element to the document to get the click functionality to work. I haven't tested extensively on other browsers how necessary this is, but it is necessary on some at least, so I recommend the following modification:
var content = document.getElementById("elem").innerHTML;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
// Set hidden so the element doesn't disrupt your page
dl.setAttribute('visibility', 'hidden');
dl.setAttribute('display', 'none');
// Append to page
document.body.appendChild(dl);
// Now you can trigger the click
dl.click();
Figured it out: I had to do `
function myAlert(){
var content = document.getElementById("elem").innerHTML;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
dl.click();
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('click', myAlert);
});
i am working on a mobile website with html,js and css.i have created tag through HTML5 DOM & assigned functions to it. It's not working.
My html code(which i have tried thro' DOM method);
<script>
var addExhibits = document.getElementById('mycontent');
function mytest()
{
var div = document.createElement('div');
div.id = 'rateMe';
var anchor = document.createElement('a');
anchor.id="_1";
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
div.appendChild(anchor);
addExhibits.appendChild(div);
}
</script>
<body><div id='mycontent' title="Rate Me..."></body>
Code(statically created tag - works fine)
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>
rate(this) is a function in external JS(http://reignwaterdesigns.com/ad/tidbits/rateme/)
Your event handler just assign the result of the respective function calls here:
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
I assume you want them to execute in case of the event instead:
var that = this;
anchor.onclick = function(){ rateIt(that); };
anchor.onmouseover = function(){ rating(that); };
anchor.onmouseout= function(){ off(that); };
You don't call your mytest() function anywhere. That's the first thing I see. The other thing is that you are putting your script above your div (mycontent) so the div has not yet been created when your script is read. But I don't completely understand what your aim is here or what exactly your problem is.
You don't need to pass this.
you can access your element inside the function in many ways.
var addExhibits=document.getElementById('mycontent'),
rateIt=function(e){
e=e||window.event;
var target=e.target||e.srcElement;//polyfill for older browser
console.log(this,target);
},
rating=function(e){
console.log(this,e.target);
},
off=function(e){
console.log(this,e.target);
},
mytest=function(){
var div=document.createElement('div'),
a=document.createElement('a');
div.id='rateMe';
a.id="_1"; // id's shouldn't contain _ - & numbers(1st letter) even if it works.
a.onclick=rateIt;
a.onmouseover=rating;
a.onmouseout=off;
div.appendChild(a);
addExhibits.appendChild(div);
};
this way you also don't create memory leaks.
ps.: that external js example you using is written very bad.
to make your example work you need to change the strange me/num/sel variables in the external js with the proper one (this/e.target/e.srcElement).
I want to preview content,when i click on the anchor tag,
var profiledemo = profiles.split(",");
for (var pd = 0; pd < profiledemo.length; pd++) {
var mydiv = document.getElementById("Profile");
var aTag = document.createElement('a');
aTag.setAttribute('href');
aTag.innerHTML = profiledemo[pd];
mydiv.appendChild(aTag);
aTag.onclick = function () {
alert("profiles anchor tag called");
}
}
I am able to display multiple docs and for those docs i put anchor tag using above,now I want,when user click on the particular tag I have to display that doc content which is in database.
Binding events in plain javascript is not much convenient, cause IE and other browsers offer different API, so you'll have to check for browser type and maintain cross-browser compatibility.
You'd better use jQuery.
$(aTag).click(function() { alert("..."); });
By the way is it necessary to construct the anchor programmatically? I'd recommend to embed html anchor and display when necessary.