Reputation: 557
I am trying to create a little jQuery switch plugin.
Here is my code:
(function($){
$.fn.slideSwitch = function (options) {
var settings = $.extend({
defaultSide: "left",
backgroundColor: "red",
toggleSize: 30,
toggleColor: "white",
speed: 100
}, options );
return this.each(function() {
$this = $(this);
var gap = Math.round(settings.toggleSize * 0.03);
if (gap < 1) {gap = 1}
$this.css({
width: (settings.toggleSize * 2) + "px",
backgroundColor: settings.backgroundColor,
borderRadius: settings.toggleSize + "px",
overflow: "hidden",
padding: gap + "px"
})
var marginLeft = 0;
if (settings.defaultSide == "right") {
marginLeft = settings.toggleSize;
}
var toggle = $("<div>").addClass("ssToggle").css({
width: settings.toggleSize,
height: settings.toggleSize,
borderRadius: settings.toggleSize,
backgroundColor: settings.toggleColor,
float: settings.defaultSide,
marginLeft: marginLeft
});
$this.html(toggle);
$this.click(function() {
var tggl = $(this).find(".ssToggle");
console.log("margin-left:", tggl.css("margin-left"));
if (parseInt(tggl.css("margin-left")) == 0) {
console.log("moving to the right");
tggl.animate({ "margin-left": settings.toggleSize + "px" }, settings.speed);
if (settings.defaultSide == "right") { $(this).trigger("switchedOn"); }
} else {
console.log("moving to the left");
tggl.animate({ "margin-left": 0 }, settings.speed);
if (settings.defaultSide == "left") { $(this).trigger("switchedOn"); }
}
$(this).trigger("switched");
})
});
};
}(jQuery));
$(function() {
$(".ssSwitch").slideSwitch({
toggleSize: 30,
speend: 40,
defaultSide: "right"
}).on("switchedOn", function(e) {
console.log("switched on!");
});
});
<div class="ssSwitch"></div>
Live Demo: https://jsfiddle.net/cutsomeat/zd6ucc5u/
When I have the defaultSide option set to "left" it works fine. However, when I have the defaultSide option set to "right", something strange happens. The css "margin-left" property has changed like it's supposed to, yet you don't see any movement of the element. The css will keep changing back and forth, but the element will remain in the original position.
Can anyone explain to me why this is happening?
Upvotes: 0
Views: 42
Reputation: 137
You have a redundant styling on your "button" element, float "right", which makes the margin you are setting irrelevant. Remove the line
float: settings.defaultSide,
And it should be ok.
See updated fiddle
Upvotes: 1
Reputation: 870
By commenting out this line, all works fine:
float: settings.defaultSide,
Try it: Demo here
Upvotes: 1