How can I simplify this repetitive jquery?
This code allows me to show / hide a custom message msg_one
msg_two
msg_three
when the corresponding div is hovering / not moving. The corresponding message is injected in #screen div
and then show / hide is applied. The code is almost identical except for the first 2 lines #one vs #two vs #three
and the displayed message msg_one msg_two msg_three
.
How can I simplify this into fewer lines of code to avoid repetition?
var msg_one = "message 1";
var msg_two = "message 2";
var msg_three = "message 3";
$("#one").hover(function() {
$("#screen").html(msg_one).show();
}, function(){
$("#screen").html("").hide();
});
$("#two").hover(function() {
$("#screen").html(msg_two).show();
}, function(){
$("#screen").html("").hide();
});
$("#three").hover(function() {
$("#screen").html(msg_three).show();
}, function(){
$("#screen").html("").hide();
});
thank.
source to share
You can extend jQuery for example:
$.fn.hover_message = function (message) {
$(this).bind("hover", function() {
$("#screen").html(message).show();
}, function(){
$("#screen").html("").hide();
});
}
And use a function like:
$("#one").hover_message(msg_one);
$("#two").hover_message(msg_two);
$("#three").hover_message(msg_three);
source to share
You can put each of the three messages in the attribute of the title
corresponding one <div>
. Then you can add a class to the div and:
$('.hover-div').hover(function() {
var msg = $(this).attr('title');
$("#screen").html(msg).show();
}, function(){
$("#screen").html("").hide();
});
I hope the code works, I wrote this out of my head :). Anyway, the idea is fine.
source to share
I would create a simple plugin that can be used long term:
<script type="text/javascript">
(function($){
$.fn.hoverScreen = function(options){
var config = $.extend({}, $.fn.hoverScreen.defaults, options);
return this.each(function(){
var $this = $(this);
$this.hover(function(){
config.screenElem.html(config.text).show();
}, function(){
config.screenElem.html('').hide();
});
});
}
$.fn.hoverScreen.defaults = {
screenElem: null,
text: ''
}
})(jQuery);
</script>
Usage will now be very simple:
$(function(){
$.fn.hoverScreen.defaults.screenElem = $("#screen");
$("#one").hoverScreen({ text: 'message one' });
$("#two").hoverScreen({ text: 'message two' });
});
source to share