Link to home
Start Free TrialLog in
Avatar of depassion
depassionFlag for Philippines

asked on

Jquery with rails 3

this jquery code works when referenced internally but when i place it in the application.js file. it dosen't work
working when referenced like this:

##application.html.erb
<script type="text/javascript">  
	$(function () {
		setInterval("rotateImages()", 2000);

	});

	function rotateImages () {
		var oCurPhoto = $("#slideshow div.current");
		var oNxtPhoto = oCurPhoto.next();
		if (oNxtPhoto.length == 0)
			oNxtPhoto = $("#slideshow div:first");

		oCurPhoto.removeClass('current').addClass('previous');
		oNxtPhoto.css({ opacity: 0.0 }).addClass('current').animate({ opacity:1.0 }, 1000, 
			function () {
				oCurPhoto.removeClass('previous');
			});	
	}


but not like this:

##application.html.erb
	<%= javascript_include_tag "application" %>
  <%= javascript_include_tag "jquery-1.4.3" %>
	<%= javascript_include_tag "rails" %>
  <%= csrf_meta_tag %>

##application.js
(function () {
	setInterval("rotateImages()", 2000);

});

function rotateImages () {
	var oCurPhoto = $("#slideshow div.current");
	var oNxtPhoto = oCurPhoto.next();
	if (oNxtPhoto.length == 0)
		oNxtPhoto = $("#slideshow div:first");

	oCurPhoto.removeClass('current').addClass('previous');
	oNxtPhoto.css({ opacity: 0.0 }).addClass('current').animate({ opacity:1.0 }, 1000, 
		function () {
			oCurPhoto.removeClass('previous');
		});	
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kristinalim
kristinalim
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I believe that's partially correct; but the standard Rails JS library (Prototype) also uses the $ tag, so I think you have to also tell jQuery to redefine the $ tag to something else, like this:
  jQuery.noConflict();
That will change the jQuery $ variable to jQuery

See http://api.jquery.com/jQuery.noConflict/ for more information.
Definitely as JESii said, you would need jQuery.noConflict() if you also include the Prototype library.

By default the Prototype library is included in the Javascript expansion :defaults, so you need this if have something like:

<%= javascript_include_tag :defaults %>

or:

<%= javascript_include_tag "prototype" %>

in your layout.