Search code examples
jquerymousedown

jQuery mousedown() only runs once


I'm trying to create a script to implement a tab functionality because .tabs() wasn't an option; it required them to be a list. It seems to work once, but clicking either div / tab again doesn't work.

$(document).ready(function() {

  var mt = $("#maintab");
  var at = $("#admintab");

  $("#tab-2").hide();  
  mt.css('background-color','#00FF00');
  mt.css('color','black');

  mt.mousedown(function() {
    $(this).css('background-color','#00FF00');
    $(this).css('color','black');
      at.css('background-color','black');
      at.css('color','#00FF00');
        $("#tab-2").hide();
        $("#tab-1").show();
  });

  at.mousedown(function() {
    $(this).css('background-color','#00FF00');
    $(this).css('color','black');
      mt.css('background-color','black');
      mt.css('color','#00FF00');
        $("#tab-1").hide();
        $("#tab-2").show();
  });

});

What could be the issue? I've linked to the latest jQuery and UI in the Markup as well as gone through to check the id's and classes. Everything checks out. here's a jsfiddle: http://jsfiddle.net/S7FLg/


Solution

  • The problem is your are using duplicate id, which is one of the MUST NOT DO THING in HTML. In Short ,id attributes must be unique within the whole document.

    So to counter that you should use class instead ...

    <p  class="taba maintab">Main</p>
    <p  class="taba admintab">Admin</p>
    

    And you can see the Updated Working Fiddle here

    P.S

    I have used the existing code in fiddle and haven't change the id of the the <p>as it distort the design. And , Why use two different block of tabs ? The Admin and Main tab are common for both div.