air
air

Reputation: 6264

setting variables and values in html & js

i have one js file in that js file i have following variables

 var image_path="images";
 var style_path="style";

i want to use these variables in html file(s)

like in image statement

       <img src="path from js/logo.gif">

or in style sheet statement

       <link rel="stylesheet" href="path from js/constant.css" type="text/css" />

Basic idea behind this is: if we change name of image folder or path of image folder we only do change in one JS file not 1000 html files.

same for style sheet.

or any other way to do same in java script or Jquery

Thanks

Upvotes: 0

Views: 226

Answers (4)

Rich
Rich

Reputation: 36806

I'm partial to jQuery for this. I agree with the crowd that server side is probably better, but if you gotta do it on the client, you could do the following.

add a class to img elements that should be effected (or skip this aspect of my example if it should apply to all...I just wanted to demonstrate that with jQuery you could make it conditional and use the class selector to do so).

ex: <img class="relative_url" src="logo.gif" /> or: <img class="img_style relative_url" src="logo.gif" /> (if the image already has a class)

then, you could use a function like the following which on page load (via $(document).ready()) gets all img elements that match the class name and iterates over them prepending the root path.

Please excuse my syntax and take this as pseudo code...I haven't done web/javascript/jquery stuff in a while

$(document).ready(function(){
    fixRelativeUrls();
});

function fixRelativeUrls()
{
    $("img.relative_url").each(function(index) {
        $(this).src = image_path + "/" + $(this).src;
    });
}

Upvotes: 2

questzen
questzen

Reputation: 3287

Did you consider usage of <base> tag? Why not may I ask :)

Upvotes: 2

Quentin
Quentin

Reputation: 943142

You can't do this sensibly. You would have to dynamically generate all the content with JavaScript — which would hide it from search engines and anyone without JS available.

You would be better off using a template engine of some kind.

Template-Toolkit can be driven from a server side script, or used to generate static pages for upload (e.g. with ttree).

You can then do things like:

[% 
    image_path = "images";
    style_path = "style";
 %]

And then:

[% INCLUDE "common.tt"; %]
<link rel="stylesheet" href="[% style_path %]/constant.css" type="text/css" />

They have a tutorial for web page authoring in TT.

Upvotes: 0

SLaks
SLaks

Reputation: 887255

You can use document.write (or jQuery) to create tags:

document.write('<img src="' + image_path + '/logo.gif">');

Note that the variables must be set before the call.

However, it's best to do this in server-side code.

Upvotes: 0

Related Questions