Hi,

I am a bit frustrated right now. I'm converting an existing site to Drupal and spent about an hour on the Drupal site trying to find information on how to insert Javascript (that is already created) into a page. Normally I'd put it in a separate file and include it in a header like this:

However, since Drupal apparently has no concept of separate files, I wasn't sure what to do. I could include all my javascript code in the head in page.tpl.php, but that doesn't seem like a good practice. I found this thread: http://drupal.org/node/146580 so I created a new block type called "Script" and included it in the head of the appropriate page. I can see it in a div in the header like this:

" + addr + "<\/a>" + endpunct); }; function generate_atberkeleyedu_email(username, endpunct) { var domain = "berkeley.edu"; var atsign = "@"; var addr = username + atsign + domain; if(arguments.length < 2) { endpunct = ""; }; document.write( "<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" + addr + "<\/a>" + endpunct); };-->

However, when I try to reference the code in a page like this:

Test email obfuscation:

Nothing happens!

This is just to test a simple javascript function. To make matters worse, I'm trying to implement this slideshow javascript application which relies on a particular file structure. I'm assuming Drupal doesn't have a concept of a file being able to reference another file because it's in the same directory, so how would I handle this?

The file structure is organized like this:

slideshow
-images
-- imgname.jpg
-- etc.
-pages
--pagename.html
--etc.
-thumbnails
-- imgname.jpg
-- etc.
- index.htm
- thumbnailframe.htm
- userselections.txt

Any help on even the simple question about how to get javascript working would be MUCH appreciated!

Thank you,
Allison

Comments

abloodworth’s picture

So part of the first function was cut off. It should be:

  <div id="header-region" class="clear-block"><div id="block-block-2" class="clear-block block block-block">


  <div class="content"><script language="javascript">
<!--
function generate_ucb_email(username, hostname, endpunct) {
	var domain = ".berkeley.edu";
	var atsign = "&#64;";
	var addr = username + atsign + hostname + domain;
	if(arguments.length < 3) {
		endpunct = "";
	};
	document.write(
		"<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" +
		addr + "<\/a>" + endpunct);
};

function generate_atberkeleyedu_email(username, endpunct) {
	var domain = "berkeley.edu";
	var atsign = "&#64;";
	var addr = username + atsign + domain;
	if(arguments.length < 2) {
		endpunct = "";
	};
	document.write(
		"<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" +
		addr + "<\/a>" + endpunct);
};-->
</script></div>
</div>

And where I inserted the javascript code, the drupal site was apparently running it. I will include the code in 'code' tags below:


Test email obfuscation: <!--
generate_ucb_email ("shelw","berkeley");
generate_atberkeleyedu_email("shelw");
-->

Interestingly, the results of running the function display the same way on this page as on my site: meaning, it looks like the function is being run because it is gone, not appearing in a comment or anything, but if you view source you can see it's not generating anything. I am using this function on another site in *exactly* the same way as I am here, so I'm not sure why if it is running it would output nothing.

Thanks again,
Allison

ximo’s picture

Maybe the reason it isn't output is because the default input filter (which I assume you're using) doesn't allow JavaScript code. Changing the input filter for the textarea of the block to Full HTML might make it output the JavaScript.

Joakim Stai – Kollegorna

erika’s picture

I'm also having the same problem and I've default input type as full html and I've added extra tags by configurig it
Only local images are allowed.

n all....but nothing helps I want a banner rotator in my site...i need java script for that..'m working on it for long but I'm not able to achieve what I want. I even tried the following node http://drupal.org/node/146580#comment-235493 but its not working for me my code is
<html>
<head>

<script language="JavaScript" type="text/JavaScript">


var slideimages=new Array()
var slidelinks=new Array()

function slideshowimages(){
  for (i=0;i<slideshowimages.arguments.length;i++){
  slideimages[i]=new Image()
  slideimages[i].src=slideshowimages.arguments[i]
  }
}

function slideshowlinks(){
  for (i=0;i<slideshowlinks.arguments.length;i++)
  slidelinks[i]=slideshowlinks.arguments[i]
}

function gotoshow(){
  if (!window.winslide||winslide.closed)
    winslide=window.open(slidelinks[whichlink])
  else
    winslide.location=slidelinks[whichlink]
    winslide.focus()
}
//-->
</script>
</head>
<body>
<a href="javascript:gotoshow()"><img src="http://localhost/?q=india" name="slide" border=0></a>

<script>
<!--
//configure the paths of the images, plus corresponding target links
slideshowimages("http://localhost/?q=india", "http://localhost/?q=spring", "http://localhost/?q=just")
slideshowlinks("http://localhost/?q=firsturl", "http://localhost/?q=secondurl","http://localhost/?q=thirdurl")

//configure the speed of the slideshow, in miliseconds
var slideshowspeed=4000
var whichlink=0
var whichimage=0

function slideit(){
  if (!document.images)
    return
    document.images.slide.src=slideimages[whichimage].src
    whichlink=whichimage

  if (whichimage<slideimages.length-1)
    whichimage++
  else
    whichimage=0
    setTimeout("slideit()",slideshowspeed)
}
slideit()
//-->
</script>
</body>
</html>
I created this as block named scripts and placed it in the header and I'm using zen theme Wat I see in the home page is the following codevar slideimages=new Array() var slidelinks=new Array() function slideshowimages(){ for (i=0;i Any suggestions drupalleres pl help
abloodworth’s picture

Show us the source from your actual page...it looks like your javascript code needs to be enclosed in

tags. See my other posts here for examples.

erika’s picture

Thanks ALlison,
Still need help....This is my code for the actual page.I'm using zen theme
What I did was

    Go to administer >>blocks
    Create new block
    In the block body place the javascript code
    Save block
    Place the block in the header area
    I've wriiten the javascipt code in the new input frmat called "Scripts" not enabling any of the filter...I created in blocks

My actual page code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
  <title>dayspringsoft | we will win</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript"><!--
  var BASE_URL = "/";
--></script>

<!--[if lt IE 7]>
    <script type="text/javascript" src="/misc/jquery.js"></script>
    <script type="text/javascript" src="/misc/drupal.js"></script>
    <script type="text/javascript" src="/modules/nice_menus/nice_menus.js"></script>
    <![endif]-->
<link rel="alternate" type="application/rss+xml" title="dayspringsoft RSS" href="http://localhost/?q=rss.xml" />

<link rel="shortcut icon" href="/themes/zen/zen-fixed/favicon.ico" type="image/x-icon" />

  <style type="text/css" media="all">@import "/modules/book/book.css";</style>
<style type="text/css" media="all">@import "/modules/forum/forum.css";</style>
<style type="text/css" media="all">@import "/modules/img_assist/img_assist.css";</style>
<style type="text/css" media="all">@import "/modules/nice_menus/nice_menus.css";</style>
<style type="text/css" media="all">@import "/modules/node/node.css";</style>
<style type="text/css" media="all">@import "/modules/system/defaults.css";</style>
<style type="text/css" media="all">@import "/modules/system/system.css";</style>
<style type="text/css" media="all">@import "/modules/user/user.css";</style>

<style type="text/css" media="all">@import "/modules/lucid_menu/css/lucid_menu.css";</style>
<style type="text/css" media="all">@import "/themes/zen/zen-fixed/style.css";</style>
  <script type="text/javascript" src="/misc/jquery.js"></script>
<script type="text/javascript" src="/misc/drupal.js"></script>
<script type="text/javascript" src="/modules/img_assist/img_assist.js"></script>
<script type="text/javascript" src="/modules/lucid_menu/js/doiMenuDOM.js"></script>
<script type="text/javascript" src="/modules/lucid_menu/js/lucid_menu_custom.js"></script>
</head>

<body class="front logged-in both-sidebars">
  <div id="page">
    <div id="header">
      <div id="logo-title">
      
        <form action="/?q=search/node"  method="post" id="search-theme-form">
<div><div id="search" class="container-inline"><div class="form-item">
 <input type="text" maxlength="128" name="search_theme_form_keys" id="edit-search-theme-form-keys"  size="15" value="" title="Enter the terms you wish to search for." class="form-text" />
</div>
<input type="submit" name="op" id="edit-submit" value="Search"  class="form-submit" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="872562d82a473775ac7670334f0d4e16"  />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form"  />
</div>

</div></form>
      
                  <a href="/" title="Home">
            <img src="/drupalfiles/zen-fixed_logo.jpg" alt="Home" id="logo" />
          </a>
                
        <div id="name-and-slogan">
        
                  <h1 id='site-name'>
            <a href="/" title="Home">
              dayspringsoft            </a>
          </h1>

                
                
        </div> <!-- /name-and-slogan -->
        
      </div> <!-- /logo-title -->
     
      
      <div id="navigation" class="menu  ">
                    
                </div> <!-- /navigation -->
      
              <div id="header-region">
                    <div id="block-block-4" class="block block-block">  
  <div class="blockinner">
    <h2 class="title">  </h2>

    <div class="content">
      <table align="right"><tr><td><a href="http://localhost/?q=logout">Logout </a></td></tr></table><br class="clear" />    </div>    
  </div>
</div>
<div id="block-block-10" class="block block-block">  
  <div class="blockinner">
    <h2 class="title">  </h2>
    <div class="content">
      <html>

<head>

<script language="JavaScript" type="text/JavaScript">


var slideimages=new Array()
var slidelinks=new Array()

function slideshowimages(){
  for (i=0;i<slideshowimages.arguments.length;i++){
  slideimages[i]=new Image()
  slideimages[i].src=slideshowimages.arguments[i]
  }
}

function slideshowlinks(){
  for (i=0;i<slideshowlinks.arguments.length;i++)
  slidelinks[i]=slideshowlinks.arguments[i]
}

function gotoshow(){
  if (!window.winslide||winslide.closed)
    winslide=window.open(slidelinks[whichlink])
  else
    winslide.location=slidelinks[whichlink]
    winslide.focus()
}
//-->
</script>
</head>
<body>
<a href="javascript:gotoshow()"><img src="http://localhost/?q=india" name="slide" border=0></a>

<script>
<!--
//configure the paths of the images, plus corresponding target links
slideshowimages("http://localhost/?q=india", "http://localhost/?q=spring", "http://localhost/?q=just")
slideshowlinks("http://localhost/?q=firsturl", "http://localhost/?q=secondurl","http://localhost/?q=thirdurl")

//configure the speed of the slideshow, in miliseconds
var slideshowspeed=4000
var whichlink=0
var whichimage=0

function slideit(){
  if (!document.images)
    return
    document.images.slide.src=slideimages[whichimage].src
    whichlink=whichimage

  if (whichimage<slideimages.length-1)
    whichimage++
  else
    whichimage=0
    setTimeout("slideit()",slideshowspeed)
}
slideit()
//-->
</script>
</body>
</html>
    </div>    
  </div>
</div>
<div id="block-lucid_menu-169" class="block block-lucid_menu">  
  <div class="blockinner">
abloodworth’s picture

The problem was not the default input filter. I had created a special input format called "Scripts" which had *none* of the filters turned on and created a block using this format which I put in the header. This is what I believe this post: http://drupal.org/node/146580 was advising me to do, but it is very unclear where this block should be placed. There seems to be no way to put blocks inside the html 'head', only the 'header' so that's where I put it but that work. Then I updated page.tpl.php to put ithe javascript function itself in my html 'head,' but that didn't work either so I put a file called functions.js containing the functions in the /files/ directory and referenced it this way in the html 'head' using page.tpl.php:

	<script language="javascript" src="/files/functions.js">
	</script>
</head>

This worked. Then I went back and put the scripts themselves back in the 'head' via page.tpl.php, removing the reference to the file above, and that worked, too. Maybe I had a syntax error the first time?


	<script language="javascript">
	<!--
	function generate_ucb_email(username, hostname, endpunct) {
		var domain = ".berkeley.edu";
		var atsign = "&#64;";
		var addr = username + atsign + hostname + domain;
		if(arguments.length < 3) {
			endpunct = "";
		};
		document.write(
			"<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" +
			addr + "<\/a>" + endpunct);
	};

	function generate_atberkeleyedu_email(username, endpunct) {
		var domain = "berkeley.edu";
		var atsign = "&#64;";
		var addr = username + atsign + domain;
		if(arguments.length < 2) {
			endpunct = "";
		};
		document.write(
			"<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" +
			addr + "<\/a>" + endpunct);
	};
	-->
	</script>

From a best practices standpoint, I'd recommending putting all your javascript in a file in the /files/ directory and referening it from inside the html 'head' as I did above. I really have no idea why someone would recommend putting it in it's own block when I don't see a way to put the block into the html 'head'. Per this tutorial, the only time Javascript is put in somewhere other than the head or an extrnal file is when it's put "within the body tag" ... "if you want the script to run when the page loads." http://www.tizag.com/javascriptT/javascriptheadnbody.php

abloodworth’s picture

Oops, the place for your javascript file is actually probably the /scripts/ directory. So it should be:

	<script language="javascript" src="/scripts/functions.js">
	</script>
</head>

And I just realized Javascript *should* work in the body by reading more of the tutorial above. I was able to get it working in my "Scripts" block in the header because there was a *small* problem with the javacript. I can't believe it's this picky, but apparently changing my closing tag from:


	};-->
	</script>

to:

	};
	-->
	</script>

...fixed the problem.

erika’s picture

do you mean to say to put the code in the page.tpl.php

 <script language="javascript" src="/scripts/functions.js">
</script>
</head>

Really sorry if I'm silly.but pl help me
Thanks

abloodworth’s picture

Yes, I'm sorry I did mean to put this code in page.tpl.php. At least that's what I ended up doing! Additionally, I discovered that the Drupal javascript code is in /etc/, not scripts, so I'd say that's the place to put it.

abloodworth’s picture

Another place to put javascript code is in the content window on an individual page. I just put it above my content. For instance:

	<script language="javascript">
	<!--
	function generate_atberkeleyedu_email(username, endpunct) {
		var domain = "berkeley.edu";
		var atsign = "&#64;";
		var addr = username + atsign + domain;
		if(arguments.length < 2) {
			endpunct = "";
		};
		document.write(
			"<" + "a" + " " + "href=\"" + "mail" + "to:" + addr + "\">" +
			addr + "<\/a>" + endpunct);
	};
	//-->
	</script>
Here is my actual content of a specific page
erika’s picture

I'll give a try for what you've said.Hope that helps me...

scritch’s picture

drupal_add_js should work for you - see:

http://api.drupal.org/api/function/drupal_add_js

It will import JavaScript files in the head, as normal. it also automatically imports Drupal.js and jquery.js the first time it's called.

Also note that Drupal keeps .js files in the misc directory. I'm putting custom ones in a directory I created at: sites/all/misc/custom.

E.g. I wrote a JavaScript function to clear text boxes when radio buttons were selected, to be use in a form I created (using the Drupal Forms API) within a module. I saved the function (without opening and closing script and comment tags, as usual) as textBoxClear.js in sites/all/misc/custom. Within the form builder function I added this line:

drupal_add_js('sites/all/misc/custom/textBoxClear.js');

That yielded these 3 lines within the head of the resulting html page:

<script type="text/javascript" src="/misc/jquery.js"></script>
<script type="text/javascript" src="/misc/drupal.js"></script>
<script type="text/javascript" src="/sites/all/misc/custom/textBoxClear.js"></script>