Users can choose to turn on ads. It should display ads if it finds a cookie (or not). I've been able to hack together something that seems to work and do what I need, but it is ugly and clunky. Returning the ad code from a function was the only way I could get it to display correctly. What shortcuts can I use to have only one main function that handles multiple ads?
Please take it easy on me since I'm a beginner. Any suggestions or direction would be great. Thanks.
var showadsornot = getAdCode();
// Put strings in array
var adText = [
"<h1>Ad Code 1</h1>",
"<h1>Ad Code 2</h1>",
"<h1>Ad Code 3</h1>",
"<h1>Ad Code 4</h1>"
];
// Look in container to get an array of ad elements
var container = document.getElementById('globalWrapper');
var ads = container.querySelectorAll('.displayad');
// For each element insert the string with the same index
// (i.e. the first string matches the first element, etc.
Array.from(ads).forEach(function (displayad, index) {
displayad.innerHTML = writeAdCode(showadsornot, adText[index]);
});
function getAdCode() {
var showadsornot = "1"; // or empty null
return showadsornot;
}
function writeAdCode(showadsornot, adcode) {
var newAdCodeTwo = "";
if(showadsornot){
newAdCodeTwo += adcode;
} else {
newAdCodeTwo += "<h2>No Ads For You!</h2>";
}
return newAdCodeTwo;
}
<html>
<head></head>
<body>
<div id="globalWrapper">
<!-- Ad Code #1 -->
<div class="container">
<div class="displayad"></div>
</div>
<!-- Ad Code #2 -->
<div class="container">
<div class="displayad"></div>
</div>
<!-- Ad Code #3 -->
<div class="container">
<div class="displayad"></div>
</div>
<!-- Ad Code #4 -->
<div class="container">
<div class="displayad"></div>
</div>
</div>
</body>
</html>
writeAdCodeTwo, three and four are exactly the same except that one variable is named differently. You could write a function just likewriteAdCodeTwothat takes 2 arguments - 1 for the ad text and one for the non-ad text. When you call the function just pass in the text that you want for each case.