1
votes

I'm a beginner in javascript.

I am using bootstrap to build my own website. I have a sidebar that contains information. The sidebar should be flexible from the left or the right as the float attribute goes on.

If the float is left, it will be perfectly on left side. Same goes with right one. so there's no issue in CSS or HTMl what so ever.

The javascript part goes like this:

$(document).ready(function() {
$('#menu-toggle').on('click',function() {                   
        $('.sidebar').css({
            'float':'right'

        })
      });
var sidebarFloat = $('.sidebar').css('float');
$('.sidebar').hover(function () {
    if (sidebarFloat == 'left'){
     $(this).stop().animate({left:"0px"},500)
     var width = $(this).width() -10;
      $(this).stop().animate({left:- width  },500);
    alert("Float left");
 }
    else if (sidebarFloat == 'right'){
     $(this).stop().animate({right:"0px"},500)
     var width = $(this).width() -10;
      $(this).stop().animate({left:+ width  },500);
    alert("Float right");    
 }
   },function () {

});
});

A button that should switch between float:left or float:right

It's originally float:left, the button switches to float:right

When in regular side 'float:left', I hover and the effect goes on + sending a messagebox saying it's on the left. as I wrote in the alert

the button changes the CSS in the browser preview. so in the preview, it's float:right

However when I hover after changing the float, it says float left in the messagebox. which means it reads from the CSS file instead from the live part in the browser. IDK how to explain it but this is what I discovered so far and IDK if it's right or wrong

Therefore, there's nothing being changed due its incapability of reading the statement :- "else if (sidebarFloat == 'right')" because to the javascript side, it's always float:left.

1
You're not changing the float css in either of your if statments, just the animation. It will be set to what it's set as at the beginning or after it's changed to 'right' on toggle click. - Anders Elmgren

1 Answers

0
votes

This is because your variable sidebarFloat is read on page load and you never change value of this variable in your code, so it is always left.

You have to change the value of your variable when you hover over your sidebar.

$('.sidebar').hover(function () {
  sidebarFloat = $(this).css('float');
  if (sidebarFloat == 'left') {
    $(this).stop().animate({left:"0px"},500)
    var width = $(this).width() -10;
    $(this).stop().animate({left:- width  },500);
    alert("Float left");
  } else if (sidebarFloat == 'right') {
    $(this).stop().animate({right:"0px"},500)
    var width = $(this).width() -10;
    $(this).stop().animate({left:+ width  },500);
    alert("Float right");    
}