Posted by bernar on December 10, 2012 at 12:50am
I'm using a couple of JQuery plugins in my new/first Drupal site. I'm trying to make a simple javascript code to work but can't find a simple solution on the internet.
I have JQuery files added to the .info file and they show up in the html code
I have some inline code in a page and it's working great. This is the code that works:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
wrap: 'circular'
});
});
</script>THE PROBLEM: I have the next inline code and it's NOT working:
<script type="text/ecmascript">
$(function() {
$("ul.demo2").ytplaylist({
addThumbs:true,
autoPlay: true,
onChange: function() {
console.log('changed');
},
holderId: 'ytvideo2'});
});
</script>Could somebody tell me how to add that code to Drupal 7?
Comments
OK, Here is the answer, I
OK, Here is the answer, I hope the next person who is looking for this type of code finds it clear.
The Javascript code has to be inside the next function, Because it uses the $ sign
(function ($) {//your code here
}(jQuery));
The example (my solution):
<script type="text/javascript">(function ($) {
$(document).ready(function() {
$(function() {
$("ul.demo2").ytplaylist({
addThumbs:true,
autoPlay: true,
onChange: function() {
console.log('changed');
},
holderId: 'ytvideo2'});
});
});
}(jQuery));
</script>
Note while the wrapper is
Note while the wrapper is important, its the use of ready() [or behaviors which is the preferred Drupal approach) which is key here. Without it there is no guarantee that ul.demo2 is defined yet.