Changing Background Color On Div - Swap Color With Tabs
Solution 1:
That's really messy ... I detected some unnecessary routes in your code:
1) Use ids starting with a letter like #tab1 and never numbers alone. 2) No need to encapsulate this process in a function. This is a straightforward procedure that doesn't need to be addressed like a repetitive pattern. 3) Do not call the function inside the href attribute. Use onclick to run JS click instructions instead.
Use this approach instead: JSFIDDLE
$(function () {
$(".tab").click(function () {
var tab = $(this),
dataTab = tab.attr('data-tab');
tab.addClass('active').siblings('.tab').removeClass('active');
$('#'+dataTab).show().siblings().hide();
});
});
Solution 2:
I would recommend using a class for changing the state of your links.
Add this in css
.active{
background-color: #008800;
}
Change your click function to this
$(".tabs").click(function () {
$(".active").removeClass("active");
$(this).addClass('active');
});
Check it out here in JSFiddle
Solution 3:
I think you should give those div a class for eg: .bg
and then in you should change in jQuery the background color like here
.
Solution 4:
Use jQuery as you have already load it. And try not to mesh up your code.
var openTab = null;
functionswapin(newTab){
if(openTab != null){
openTab.css('background-color','#7D135A');
$(openTab.data('tab-element')).css('display',"none");
}
newTab.css('background-color','#008000');
$(newTab.data('tab-element')).css('display',"block");
openTab = newTab;
}
$(function () {
$(".tabs .tab").click(function () {
swapin($(this));
});
});
.tabs.tab{
background-color: #7D135A;
border-radius: 2px2px00;
height: 50px;
width: 90px;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
padding-bottom: 0px;
color: #FFFFFF;
cursor: pointer;
}
.contain {
width: 500px;
height: 200px;
border: 1px;
border-style: solid;
border-color: #7D135A;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="tabs"><aclick="swapin()"class="tab"data-tab-element="#1">One</a><aclick="swapin()"class="tab"data-tab-element="#2">Two</a><aclick="swapin()"class="tab"data-tab-element="#3">Three</a></div><divid="contain"class="contain"><divid="1"style="display: none;">
One Content
</div><divid="2"style="display: none;">
Two Content
</div><divid="3"style="display: none;">
Three Content
</div></div>
Post a Comment for "Changing Background Color On Div - Swap Color With Tabs"