javascript - How to use a image file relative to a url path? - javascript

Is there a way to use a image url relative path in a javascript file (just like the css files)?
for testing i used 2 divs and displayed a gif in background using css in 1st and using js in second:
-my file directory is:
root/index.html
root/module1/test.css
root/module1/test.js
root/module1/img.gif
-index.html code:
<html>
<head>
<link href="module1/test.css" rel="stylesheet" type="text/css">
</head>
<body>
<P id="p1"> Line 1 </P>
<P id="p2"> Line 2 </P>
<script type="text/javascript" src="module1/test.js"></script>
</body>
</html>
-test.css code:
#p2 {background: url('img.gif')}
in the css I can use the relative path.
-test.js code:
document.getElementById("p1").style.backgroundImage = 'url(./module1/img.gif)';
but in the js I have to use the absolute path or it doesn't work.
-img.gif - you can use any gif image.
I've tried to search the web but I was just getting confused :(
plz help :)
Ps: if you know a solution in jquery i also appreciate.

In a CSS style sheet, the path is interpreted relative to the style sheet.
If you specify a path later, using JavaScript, it will be interpreted relative to the document.
You can still use relative paths, but, as said, they will have to be relative to the document. So it would have to be
url("module1/img.gif");
But you already know that.
I don't know a way of building paths relative to the style sheet outside the style sheet.
The only workaround that comes to my mind is to define a class inside the style sheet and, instead of specifying a background image using javaScript, changing the element's class.
In the style sheet:
.p2_img_gif {background: url('img.gif')}
and when the time comes for the paragraph to get the background image, do a
document.getElementById("p2").className = "p2_img_gif";
if you need to toggle classes, or specify multiple ones, consider using jQuery's addClass() and removeClass().

As variant use element inline style
var element = document.getElementById("p1");
var imageUrl = './module1/img.gif';
element.setAttribute('style', 'background-image: url(' + imageUrl +');');

This works for me with Firefox 3.6.
<!doctype html>
<style>
div { background: red; width: 80px; height: 80px }
</style>
<script>
window.onload = function() {
document.getElementById("test").style.backgroundImage = 'url("green.png")';
}
</script>
<p>There should be no red.</p>
<div id="test"></div>
where green.png is a green pixel. Which browser are you using?

Related

Retrieving the actual DOM/css state of a web page through javascript

As you know, a web page is the union of a html file, one or more css files and one or more javascript files: the first two elements are parsed by the browser to generate the DOM and other data structures useful for the rendering of the page .
Javascript files are executed by an engine, and they can change the value of the DOM or of the data structures related to css, so that, after the execution of a javascript, the "actual status" of a web page can be different from what was statically described by the original html and css code.
I need to develop a firefox add-on that grabs the "actual status" of a web page and stores it to disk, as a couple html + css file.
For the html file is quite easy, i need to serialize the DOM. My concerns are about the css: I can traverse the DOM and for each element get its stylesheet, but it will be
extremely slow and produces a not optimized css code.
Let's make an example
I have this html code:
<html>
<head>
<title>Test</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script type='text/javascript' src="changebackground.js" > </script>
</head>
<body>
<div class="divclass" >
<form>
<h2>click to change the background</h2>
<input type="button" value="version" onclick="changebg()" />
</form>
</div>
</body>
Style.css has this definitions:
.divclass{
margin: .5in;
height: 400px;
}
body{
background-color: white;
color: blueviolet;
}
and changebackground has this code:
function changebg() {
document.body.style.backgroundColor = 'black';
}
Obviously, after clicking the button the background's color becomes black.
My goal is to write an add-on that , after this change, gives me back the css with the style's modification, i.e.:
.divclass{
margin: .5in;
height: 400px;
}
body{
background-color: black;
color: blueviolet;
}
Any ideas?
You don't actually need to traverse anything. Inline styles are already part of the, so you get that for free, e.g.:
elem.style.width = "100px";
elem.outerHTML == '<elem style="width: 100px;>";
So to produce a "dump" of the current DOM, incl. inline styles, etc. do:
var html = document.documentElement.outerHTML;
You may also want to serialize document.doctype.
In the unlikely event that a script actually messes with external stylesheets (<link rel="stylesheet">, you may do something like what I described in "Get text of a modified stylesheet" to get the current set of rules. Again, inline styles (<style> and style= attributes) are already present in .outerHTML.
EDIT: What you ask now is not possible, because this is not how inline styles work.
Consider the following html fragment:
<div>first div</div>
<div>second div</div>
Now the following code runs:
document.querySelector("div").style.background = "black";
This will cause the first div to have an inline style:
<div style="background: none repeat scroll 0% 0% black;">first div</div>
<div>second div</div>
Demo Fiddle
How would that rule look like? div { background: black; } is obviously wrong, as this would affect all divs.
You could generate new classes and/or ids, but then you need to manipulate and store the DOM, and could have used my original answer in the first place.

How to change the background image of my website everytime i click each link or url?

Ok so, I've seen so many questions on the web about this but it seems that many of it is using PHP, ASP, JQUERY and any other languages. For me I am only a little bit familiar with CSS and Java Script and that is the language I only knew. So can someone show me some code of CSS and Java Script for that question?
Anyway, I am also interested in Background on the website that will change every refresh!
Thanks in Advance!
Hey I found the sample code and it is perfectly working!
Credits to this forum: http://www.daniweb.com/web-development/web-design-html-and-css/threads/228324/load-different-background-image-when-user-refresh
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = ["Background/Background.jpg", "Background/Background2.jpg", "Background/Background3.jpg", "Background/Background4.jpg", "Background/Background5", "Background/Background6", "Background/Background7"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
<style type="text/css">
.bg {background-attachment:fixed; background-repeat: no-repeat; background-position:top right;}
</style>
</head>
<body class="bg">
<p>Some text</p>
<!-- put a lot text lines here to see that the background stays fixed. -->
<p>Some text</p>
</body>
</html>
Plenty of solution :
Store all the files in a folder.
Index the images in a database table with a index number. Generate a random number with specific range and display the image which corresponds to the random number
Rename all the images in the folder from (1 - n). Generate random number and append with /.
Once you get the random image, you can easily over write the background or any other dom component with javascript like
document.getElementByTag('body').setAttribute('style','background-image:url('+<your image>+'));
You can simplify it with jQuery too.
You can easily do it by using JQuery - just define click event for each of the link -
$(function(){
$("link1").click(function(){
$("body").css({background-image:"url('link1_image.gif')"});
});
});​
For random image load on each refresh you can directly call onload function and set random image.
$(function(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
});​
Hopefully it will work. Thanks.

Javascript to rotate between pages within ONE HTML page

I would like some help displaying contents (to different pages) within one HTML page using JavaScript.
This is a sample of what I have found so far: http://www.swan10.nl/stuff/test.htm however instead of displaying "FAQ question #blabla" in the box every time a link is clicked, I would like to display words and images like a normal content. Is there a way to do this?
I tried removing the CreateDiv function and replacing it with HTML codes but it doesn't work.
Thank you in advance :)
Umm, well you would need to use AJAX to pull the data into the page and display it in whatever method you choose. If you want to use a framework look into JQuery. It has nice AJAX functions. Otherwise read HERE
After re-reading your post I think you might just want to choose which div is displayed on a form at one time. This you can achieve by placing all of your divs in the same container. Then toggle their display css property.
Using jQuery it's as simple as
$('#divname').load('/path/to/file.html');
Note that the result should probably not include <html> and <head> tags (although you don't seem like you care about well formed HTML code).
I should probably also mention that you shouldn't make the client load content for you, that's what server side code is for.
Personally I would use the innerHTML property on one of your elements. It will allow you to add markup to that element. Check it out here: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
<html>
<head>
<title>Multiple DIV</title>
<style type="text/css">
DIV#db {
border : 1px solid blue;
width : 400px;
height : 400px;
}
</style>
<script type="text/javascript">
var Content = new Array();
Content[0] = '<i>test1</i>';
Content[1] = '<b>test2</b><br><img src =http://www.w3schools.com/images/w3schoolslogo.gif>';
Content[2] = '<u>test3</u>';
Content[3] = '<s>test4</s>';
function Toggle(IDS) {
document.getElementById('db').innerHTML = Content[IDS];
}
</script>
</head>
<body onLoad="Toggle(0,10)">
FAQ #1
FAQ #2
FAQ #3
FAQ #4
<p />
<div id="db"></div>
</body>
</html>
I updated it to work all javascripty with the innerHTML

How to change font color inside an existing script?

I get a script from a website to put it into my website, but the font color is not what I want.
The script is:
<script language="javascript" src="http://www.parstools.net/calendar/?type=2"></script>
and now I want to change the font color of it. What should I do?
I would really appreciate your help, thanks.
Examining the source of that script, it is simply writing an anchor link with document.write():
document.write("<a href='http://www.ParsTools.com/'>1389/1/31</a>");
You may want to include that script inside a <div>, and then style the anchor links within that <div> using CSS:
<div id="calendar">
<script src="http://www.parstools.net/calendar/?type=2"></script>
</div>
Then you should also add the following CSS class definition:
div#calendar a {
color: red;
}
The following is a full example:
<!DOCTYPE html>
<html>
<head>
<title>Simple Demo</title>
<style type="text/css">
div#calendar a {
color: red;
}
</style>
</head>
<body>
<div id="calendar">
<script src="http://www.parstools.net/calendar/?type=2"></script>
</div>
</body>
</html>
I assume you want to change the font colour of the HTML code produced by the script? If so, just use normal CSS in your external stylesheet and it will apply to the added content.
For example, if you want to make the text inside the element myElement a nice blue colour:
#myElement {
font-color: #0099FF;
}
If the script is not your own, then you will want to analyse the code produced by it to work out which elements you need to style in order to change the colour of the text. Many external scripts that you embed in your website contain inline CSS rules, meaning that you will have to override many elements in your external CSS stylesheet to change simple things like text colour. You may also have to add !important to the end of your CSS rule in order to override the inline styling:
#myElement {
font-color: #0099FF !important;
}

Is there a HTML opposite to <noscript>?

Is there a tag in HTML that will only display its content if JavaScript is enabled? I know <noscript> works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.
The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.
Easiest way I can think of:
<html>
<head>
<noscript><style> .jsonly { display: none } </style></noscript>
</head>
<body>
<p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
No document.write, no scripts, pure CSS.
You could have an invisible div that gets shown via JavaScript when the page loads.
I don't really agree with all the answers here about embedding the HTML beforehand and hiding it with CSS until it is again shown with JS. Even w/o JavaScript enabled, that node still exists in the DOM. True, most browsers (even accessibility browsers) will ignore it, but it still exists and there may be odd times when that comes back to bite you.
My preferred method would be to use jQuery to generate the content. If it will be a lot of content, then you can save it as an HTML fragment (just the HTML you will want to show and none of the html, body, head, etc. tags) then use jQuery's ajax functions to load it into the full page.
test.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.get('_test.html', function(html) {
$('p:first').after(html);
});
});
</script>
</head>
<body>
<p>This is content at the top of the page.</p>
<p>This is content at the bottom of the page.</p>
</body>
</html>
_test.html
<p>This is from an HTML fragment document</p>
result
<p>This is content at the top of the page.</p>
<p>This is from an HTML fragment document</p>
<p>This is content at the bottom of the page.</p>
First of all, always separate content, markup and behaviour!
Now, if you're using the jQuery library (you really should, it makes JavaScript a lot easier), the following code should do:
$(document).ready(function() {
$("body").addClass("js");
});
This will give you an additional class on the body when JS is enabled.
Now, in CSS, you can hide the area when the JS class is not available, and show the area when JS is available.
Alternatively, you can add no-js as the the default class to your body tag, and use this code:
$(document).ready(function() {
$("body").removeClass("no-js");
$("body").addClass("js");
});
Remember that it is still displayed if CSS is disabled.
I have a simple and flexible solution, somewhat similar to Will's (but with the added benefit of being valid html):
Give the body element a class of "jsOff". Remove (or replace) this with JavaScript. Have CSS to hide any elements with a class of "jsOnly" with a parent element with a class of "jsOff".
This means that if JavaScript is enabled, the "jsOff" class will be removed from the body. This will mean that elements with a class of "jsOnly" will not have a parent with a class of "jsOff" and so will not match the CSS selector that hides them, thus they will be shown.
If JavaScript is disabled, the "jsOff" class will not be removed from the body. Elements with "jsOnly" will have a parent with "jsOff" and so will match the CSS selector that hides them, thus they will be hidden.
Here's the code:
<html>
<head>
<!-- put this in a separate stylesheet -->
<style type="text/css">
.jsOff .jsOnly{
display:none;
}
</style>
</head>
<body class="jsOff">
<script type="text/javascript">
document.body.className = document.body.className.replace('jsOff','jsOn');
</script>
<noscript><p>Please enable JavaScript and then refresh the page.</p></noscript>
<p class="jsOnly">I am only shown if JS is enabled</p>
</body>
</html>
It's valid html. It is simple. It's flexible.
Just add the "jsOnly" class to any element that you want to only display when JS is enabled.
Please note that the JavaScript that removes the "jsOff" class should be executed as early as possible inside the body tag. It cannot be executed earlier, as the body tag will not be there yet. It should not be executed later as it will mean that elements with the "jsOnly" class may not be visible right away (as they will match the CSS selector that hides them until the "jsOff" class is removed from the body element).
This could also provide a mechanism for js-only styling (e.g. .jsOn .someClass{}) and no-js-only styling (e.g. .jsOff .someOtherClass{}). You could use it to provide an alternative to <noscript>:
.jsOn .noJsOnly{
display:none;
}
In the decade since this question was asked, the HIDDEN attribute was added to HTML. It allows one to directly hide elements without using CSS. As with CSS-based solutions, the element must be un-hidden by script:
<form hidden id=f>
Javascript is on, form is visible.<br>
<button>Click Me</button>
</form>
<script>
document.getElementById('f').hidden=false;
</script>
<noscript>
Javascript is off, but form is hidden, even when CSS is disabled.
</noscript>
You could also use Javascript to load content from another source file and output that. That may be a bit more black box-is than you're looking for though.
Here's an example for the hidden div way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*[data-when-js-is-on] {
display: none;
}
</style>
<script>
document.getElementsByTagName("style")[0].textContent = "";
</script>
</head>
<body>
<div data-when-js-is-on>
JS is on.
</div>
</body>
</html>
(You'd probably have to tweak it for poor IE, but you get the idea.)
My solution
.css:
.js {
display: none;
}
.js:
$(document).ready(function() {
$(".js").css('display', 'inline');
$(".no-js").css('display', 'none');
});
.html:
<span class="js">Javascript is enabled</span>
<span class="no-js">Javascript is disabled</span>
Alex's article springs to mind here, however it's only applicable if you're using ASP.NET - it could be emulated in JavaScript however but again you'd have to use document.write();
You could set the visibility of a paragraph|div to 'hidden'.
Then in the 'onload' function, you could set the visibility to 'visible'.
Something like:
<body onload="javascript:document.getElementById(rec).style.visibility=visible">
<p style="visibility: visible" id="rec">This text to be hidden unless javascript available.</p>
There isn't a tag for that. You would need to use javascript to show the text.
Some people already suggested using JS to dynamically set CSS visible. You could also dynamically generate the text with document.getElementById(id).innerHTML = "My Content" or dynamically creating the nodes, but the CSS hack is probably the most straightforward to read.

Categories