jQuery noob here (don’t most posts start like that?)
I know I could do this with CSS alone however, just to make the experience a little more tactile, I’m trying to write a jQuery “spoiler” function that obfuscates a bit of text on a page if it’s marked up appropriately and reveals it on mouseover.
On the whole this works nicely – it replaces the text with some text of your choice and even matches the width of the replaced text to stop the text from reflowing. The problem comes when I add more than one spoiler class on a page – in this case it concatenates the text within each spoiler and seems to match the width of the element first matched element. It’s basically like the function can’t tell the difference between each spoiler so it puts them all together.
I must be doing something wrong on a fairly fundamental level. Can someone point out my mistake please?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spoiler test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
jQuery.fn.spoiler = function(spoilerReplaceText) {
$(this).addClass('spoilerCensored');
var spoilerText = $(this).text();
var spoilerWidth = $(this).width();
$(this).attr('spoilertext',spoilerText).text(spoilerReplaceText).width(spoilerWidth);
$(this).stop().hover(
function(){
var spoilerText = $(this).attr('spoilertext');
$(this).fadeOut(250,function(){
$(this).text(spoilerText).addClass('spoilerRevealed').removeClass('spoilerCensored').fadeIn(250);
});
},
function(){
$(this).fadeOut(250,function(){
$(this).text(spoilerReplaceText).removeClass('spoilerRevealed').addClass('spoilerCensored').fadeIn(250);
});
}
);
};
$('.spoiler').spoiler("don't touch this");
});
</script>
<style type="text/css">
.spoiler {display: inline-block;background-color: #000000;color: #000000;text-align: center;}
.spoilerCensored {color: #ffffff;}
.spoilerRevealed {background-color: #ffffff;color: #000000;}
</style>
</head>
<body>
<p>You can add a <span class="spoiler">spoiler to your content</span> very easily. All you need to do is <span class="spoiler">add a class called spoiler to each bit of text</span> you'd like to hide. There is a problem with <span class="spoiler">adding</span> more than one spoiler to a page though.</p>
</body>
</html>
you need to treat the argument as a set:
If youre using this as plugin which is essentially what you have done you also do want that snippet of code inside document ready. You want it in its own js file which you include just after jquery.
You also might want to add options/defaults:
And your usage then becomes:
Check out the plugin authoring docs for more info