I am writing a script to change which element is visible based on string in hash. The script will go on a blog page where the user can filter blog posts by category. When the user filters to a certain category, that category is appended to the url in the form of a hash link.
example.com/#categoryA
At that point, I want a text box corresponding to each set of filtered posts to appear alongside the portfolio. However, if the user has not filtered the posts, or goes from filtering posts to viewing all posts, there is a single hash in the url like this:
example.com/#
In this case, I want a default text box to be shown.
My script (below) does everything except show the default text box when the url ends in just a hash.
var frag = window.location.href.split("#");
var hashClassChange = function() {
if (window.location.hash) {
//If the url hash contains commercial, show the commercial box, hide the last active box
if (window.location.hash.indexOf('commercial') == 1) {
$('#box1').addClass("active");
$('#default').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains hospitality, show the hospitality box, hide the last active box
else if (window.location.hash.indexOf('hospitality') == 1) {
$('#box2').addClass("active");
$('#default').removeClass("active");;
$('#box1').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains municipal-institutional, show the municipal / institutional box, hide the last active box
else if (window.location.hash.indexOf('municipal-institutional') == 1) {
$('#box3').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains residential, show the residential box, hide the last active box
else if (window.location.hash.indexOf('residential') == 1) {
$('#box4').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
}
//If the url hash does not contain any string, show the default box
else if (!frag[1].length) {
$('#default').addClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box3').removeClass("active");
}
}
};
// repeats function every 500 milliseconds to check if the url hash has been changed
setInterval(hashClassChange, 500);
How do I fix this script so that the default text box shows when the url ends in a single hash?
I have a codepen set up (http://codepen.io/ben393/pen/GNVqRX) to show this in action.
window.location.hashwhich will give the hash in the form "#hospitality". Then, you should create a switch statement ( or if else ) with exact matches. Using indexOf like you are doing now may give false positives.