HTML
<!doctype html>
<html>
<head>
</head>
<body>
<button id="b1" type="button">Show Spoiler</button>
<p id="p1" style="display:none"> This is a damn paragraph.</p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JS
function bindEvent(element, eventName, eventHandler) {
var el = $(element)[0];
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false)
} else if (el.attachEvent) {
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent('#b1', 'click', function() {
$('#p1').toggle('blind');
if ($('#b1').text() == 'Show Spoiler') {
$('#b1').text('Hide Spoiler');
} else if ($('#b1').text() == 'Hide Spoiler') {
$('#b1').text('Show Spoiler');
}
});
I’m new to jQuery and Javascript so I made this simple script to show and hide a paragraph and to change the button texts whenever clicked. My problem is that this seems a bit clunky. Is there a better, shorter, and simpler way to achieve the same result?
First of all, jQuery already normalizes DOM event listeners for you across browsers, so your
bindEventfunction isn’t necessary anymore. Here’s the short way, using some stuff you can look up yourself in the jQuery API, to do what you’re doing.Here are a few things to notice:
Your example function assumes a single spoiler
#p1and a single reveal button#b1. In production, this will probably be based on classes, like.spoilerand.spoiler-trigger, and there will be multiple spoilers on a page. In that case, you’ll need to get the value ofthis. In this example let’s assume that the reveal button is always a sibling of the spoiler itself.The jQuery
.onmethod is the cross-browser event listener function that you’ll want to start using.$(this)or$('#b1'), should be cached in local variables for performance.