开发者

What is the best solution to make a jQuery Character Cycle Plugin Unobtrusive?

开发者 https://www.devze.com 2023-04-11 17:19 出处:网络
I created a little jQuery plugin to create a character cycling effect on some event, much like the effect on yugop.com. I would like to separate the element whose event triggers the cycling from the e

I created a little jQuery plugin to create a character cycling effect on some event, much like the effect on yugop.com. I would like to separate the element whose event triggers the cycling from the element but I can't figure out how to do this without using unique ids. The best I have right is to have the element whose text is being cycled as a child of the element triggering the cycling. and select it based on an id.

Here is the demo

Here is how the plugin is called

$('.c').mouseenter(function(){
    if($(this).hasClass('cycling')==false){ 
                $(this).charcycle({'target':'#text'});  
    }
});

Here is the html markup for the elements being manipulated

<div class="c">
   <a href="#" id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit</a>  
</div> 

mousing over the div is triggering the plugin which is cycling text in the element with the id "text" which is specified when calling the plugin.

Here are the jQuery selectors I am using within the plugin

settings.targetElement=$(this).find(settings.target);
settings.quoteStr=settings开发者_JAVA百科.targetElement.text();

Any help would be appreciated, thanks!


You could use something like:

$(this).charcycle({'target': $(this).contents(":first-child") });

But probably more practically, you would use this as a default fall-back position, in the absence of being passed an explicit target.


You could use additional classes on hovered element to specify elements of what class to trigger the cycling on. Something like this might work:

$('.c').mouseenter(function(){
    if (!$(this).hasClass('cycling'))
    { 
        var prefix = 'ctarget-';
        var classes = $(this).attr('class').split(' ');
        // enumerate all the classes of this element
        for (var i in classes)
        {
            // if a class starts with a known prefix (see above)
            if (classes[i].substr(0, prefix.length) == prefix)
            {
                // then extract target class from it and use that
                $(this).charcycle({target: '.'+classes[i].substr(prefix.length)});
            }
        }
    }
});

The HTML would look like this:

<div class="c ctarget-text1">trigger</div>
<a href="#" class="text1">Lorem ipsum dolor sit amet</a>  

(By the way: not a good thing to use multiple elements with the same id, you should have probably used classes there instead.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号