Making a jQuery plugin that works on multiple elements
Hello,
I am working on a jQuery plugin and have run into an issue I did not realize existed. I am trying to instantiate my plug in against multiple elements on the page, but it is only being applied to the second element I specify. I am guessing jQuery plugins do not create new objects for each element that they are applied to but rather are a single object themselves.
I have read that widget factory may help with this but I have not tried it out yet, anyone have any advice or can anyone point me in the right direction. Here is something I threw together to illustrate my point.
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title></title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href=".css"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.4.0");</script>
<style>
#scrollmask {
width: 200px;
overflow: hidden;
height: 90px;
}
ul {
position: relative;
width: 9999px;
}
li {
display: block;
float: left;
}
</style>
</head>
<body>
<div id="scrollmask">
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</div>
<div id="scrollmask2">
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</div>
<script>
(function($) {
$.fn.scrollTool = function(settings) {
var speed = 1;
var fast = 3;
this.each(function doScroll(speed) {
element = this;
scrollItem = $(element).find("ul");
scrollLeft = function () {
newlocal = parseInt($(scrollItem).css("left")) - 1 + "px";
$(scrollItem).css("left",newlocal);
}
setInterval("scrollLeft()", 20)
})
return this;
}
})(jQuery);
$("#scrollmask2, #scrollmask").scrollTool();
$("#scrollmask").scrollTool();
</script>
</body>
</html>
Thanks for any help!