patternjavascriptMinor
Setting a cookie based on a selector
Viewed 0 times
selectorsettingcookiebased
Problem
I've got a conditional that sets a cookie based on whether a selector exists. There are other places in the code where I do something similar if the selector exists. If the selector exists I either add "nfl" or "nfl-" (notice the dash) to various attributes on the page. I'm trying to remove as much code as I can as there are about five other places I have similar code where I'm adding other attributes. I also feel like there's a better way to approach this without having to write this a ton of times:
I'm banging my head on how to condense this but can't figure this out. Please include code samples; I learn best that way.
if($(".userLocation").length > 0){I'm banging my head on how to condense this but can't figure this out. Please include code samples; I learn best that way.
if($(".userLocation").length > 0){
var user_cookie = {
name: 'nfl-user-profile',
options: {
path: '/',
expires: 365
}
};
} else {
var user_cookie = {
name: 'user-profile',
options: {
path: '/',
expires: 365
}
};
}
if($(".userLocation").length > 0){
$('header').attr("href","#nfl-city");
$('header').attr("href","#nfl-state");
} else {
$('header').attr("href","#city");
$('header').attr("href","#state");
}
if($(".userLocation").length > 0){
$('footer').attr("title","#nflcity");
$('footer').attr("title","#nflstate");
} else {
$('footer').attr("title","#city");
$('footer').attr("title","#state");
}Solution
Only thing I can think of is that wrap the condition:
then you can call like this:
jsfiddle
var hasUserLocation = function (hasFunc, noFunc) {
if ($(".userLocation").size() > 0) {
hasFunc();
} else {
noFunc();
}
}then you can call like this:
hasUserLocation(function () {
alert("has");
}, function () {
alert("no")
})jsfiddle
Code Snippets
var hasUserLocation = function (hasFunc, noFunc) {
if ($(".userLocation").size() > 0) {
hasFunc();
} else {
noFunc();
}
}hasUserLocation(function () {
alert("has");
}, function () {
alert("no")
})Context
StackExchange Code Review Q#40305, answer score: 4
Revisions (0)
No revisions yet.