How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "
";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!
I had some code created to convert a 3rd party form to jQuery AJAX with a custom redirect. On the redirect page the users name from the form was captured. The issue is that I can only capture the name once. If I try to duplicate the code to show the name multiple times it doesn't work.
Would much appreciate the help!
------Javascript for the submit button------
window.CFS = window.CFS || {};
(function () {
"use strict";
CFS.msgPleaseWait = 'Please wait...';
CFS.msgRedirect = 'Redirecting...';
CFS.nameField = '';
CFS.nameFromSubmitField = '';
CFS.redirectTo = '';
CFS.submitButtonText = '';
CFS.submitHandler = function(form) {
var $form = $(form);
var dataToPost = $form.serialize();
var urlToPostTo = $form.attr("action");
var $submitButton = $("input[type='submit']", $form);
CFS.submitButtonText = $submitButton.val();
CFS.disableSubmit($submitButton);
$.ajax({
type: 'POST',
url: urlToPostTo,
data: dataToPost,
success: function(data) {
if (CFS.redirectTo) {
$submitButton.val(CFS.msgRedirect);
if (CFS.nameField) {
var nameFieldVal = '';
if ($("input[name='" + CFS.nameField + "']", $form)) {
nameFieldVal = $("input[name='" + CFS.nameField + "']", $form).val();
}
if (nameFieldVal) {
CFS.setCookie('name', nameFieldVal, 60);
}
}
window.location.replace(CFS.redirectTo);
} else {
CFS.enableSubmit($submitButton);
}
},
error: function() {
console.log('Campaigner.com error!');
CFS.enableSubmit($submitButton);
}
});
}
CFS.disableSubmit = function($button) {
$button.attr("disabled", "disabled");
$button.val(CFS.msgPleaseWait);
}
CFS.enableSubmit = function($button) {
$button.val(CFS.submitButtonText);
$button.removeAttr("disabled");
}
CFS.setCookie = function(name, value, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = 'expires=' + d.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/';
}
CFS.getCookie = function(name) {
name += '=';
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
CFS.setNameFromSubmit = function() {
if (CFS.nameFromSubmitField) {
var elem = document.getElementById(CFS.nameFromSubmitField);
var savedName = CFS.getCookie('name');
if (elem && savedName) {
elem.innerHTML = savedName;
}
}
}
})();
------Name Field Captured-----
<p>Hello my name is <span id="nameFromSubmit">NAME HERE</span>
<script src="custom-submit.js" type="text/javascript"></script>
<script type="text/javascript">
if ((typeof CFS !== 'undefined') && CFS.setNameFromSubmit) {
CFS.nameFromSubmitField = 'nameFromSubmit';
CFS.setNameFromSubmit();
}
</script>
I am trying to create an HTML5 JavaScript game that uses Nintendo Switch Joy-Cons and motion controls. The problem is, I don't know how to detect motion controls from Joy-Cons when they are connected to my PC.
I've managed to achieve button inputs with Xbox controllers, PS4, and Joy Con using Gamepad API, but is it possible to do so with Joy-Con motion controls?
Here is the code for Gamepad API if you want to see it(Again, I'm aiming for Joy-Con motion controls):
var haveEvents = 'ongamepadconnected' in window;
var controllers = {};
function connecthandler(e) {
addgamepad(e.gamepad);
}
function addgamepad(gamepad) {
controllers[gamepad.index] = gamepad;
var d = document.createElement("div");
d.setAttribute("id", "controller" + gamepad.index);
var t = document.createElement("h1");
t.appendChild(document.createTextNode("gamepad: " + gamepad.id));
d.appendChild(t);
var b = document.createElement("div");
b.className = "buttons";
for (var i = 0; i < gamepad.buttons.length; i++) {
var e = document.createElement("span");
e.className = "button";
//e.id = "b" + i;
e.innerHTML = i;
b.appendChild(e);
}
d.appendChild(b);
var a = document.createElement("div");
a.className = "axes";
for (var i = 0; i < gamepad.axes.length; i++) {
var p = document.createElement("progress");
p.className = "axis";
//p.id = "a" + i;
p.setAttribute("max", "2");
p.setAttribute("value", "1");
p.innerHTML = i;
a.appendChild(p);
}
d.appendChild(a);
var start = document.getElementById("start");
if (start) {
start.style.display = "none";
}
document.body.appendChild(d);
requestAnimationFrame(updateStatus);
}
function disconnecthandler(e) {
removegamepad(e.gamepad);
}
function removegamepad(gamepad) {
var d = document.getElementById("controller" + gamepad.index);
document.body.removeChild(d);
delete controllers[gamepad.index];
}
function updateStatus() {
if (!haveEvents) {
scangamepads();
}
var i = 0;
var j;
for (j in controllers) {
var controller = controllers[j];
var d = document.getElementById("controller" + j);
var buttons = d.getElementsByClassName("button");
for (i = 0; i < controller.buttons.length; i++) {
var b = buttons[i];
var val = controller.buttons[i];
var pressed = val == 1.0;
if (typeof(val) == "object") {
pressed = val.pressed;
val = val.value;
}
var pct = Math.round(val * 100) + "%";
b.style.backgroundSize = pct + " " + pct;
if (pressed) {
b.className = "button pressed";
//Pressed down code here
} else {
b.className = "button";
//Release button code here
}
}
var axes = d.getElementsByClassName("axis");
for (i = 0; i < controller.axes.length; i++) {
var a = axes[i];
a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
a.setAttribute("value", controller.axes[i] + 1);
}
}
requestAnimationFrame(updateStatus);
}
function scangamepads() {
var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
for (var i = 0; i < gamepads.length; i++) {
if (gamepads[i]) {
if (gamepads[i].index in controllers) {
controllers[gamepads[i].index] = gamepads[i];
} else {
addgamepad(gamepads[i]);
}
}
}
}
window.addEventListener("gamepadconnected", connecthandler);
window.addEventListener("gamepaddisconnected", disconnecthandler);
if (!haveEvents) {
setInterval(scangamepads, 500);
}
Using this link for reference
Wei Gao explained this in a React Knowledgeable meetup last week.
You can learn how she did it through her presentation or her slides.
You can visit the talk page for more information.
I have been using this code found on Github to collect some UTM/other URL parameters.
I have been able to successfully save the parameters in a cookie, and pass those values into a hidden input form.
This code is loaded through Google Tag Manager on every page of the website.
Scenario:
-The cookie sessions exist on every page of the site as expected.
-The main website is on a non-secure HTTP connection (http://www.example.com).
-A secure page exists on the subdomain. (https://www.subdomain.example.com).
Problem: On the secure, subdomain page, I cannot get the values from none of the UTM cookies. I can get the values from the VISITORS, IREFERRER, LREFERRER, and ILANDINGPAGE cookies, but not from the UTM cookies.
Here is the code that I am using:
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
var _uf = _uf || {};
_uf.domain = ".exampledomain.com";
var UtmCookie;
UtmCookie = (function() {
function UtmCookie(options) {
if (options == null) {
options = {};
}
this._cookieNamePrefix = '_uc_';
this._domain = options.domain;
this._sessionLength = options.sessionLength || 1;
this._cookieExpiryDays = options.cookieExpiryDays || 365;
this._additionalParams = options.additionalParams || [];
this._utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
this.writeInitialReferrer();
this.writeLastReferrer();
this.writeInitialLandingPageUrl();
this.setCurrentSession();
if (this.additionalParamsPresentInUrl()) {
this.writeAdditionalParams();
}
if (this.utmPresentInUrl()) {
this.writeUtmCookieFromParams();
}
return;
}
UtmCookie.prototype.createCookie = function(name, value, days, path, domain, secure) {
var cookieDomain, cookieExpire, cookiePath, cookieSecure, date, expireDate;
expireDate = null;
if (days) {
date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expireDate = date;
}
cookieExpire = expireDate != null ? '; expires=' + expireDate.toGMTString() : '';
cookiePath = path != null ? '; path=' + path : '; path=/';
cookieDomain = domain != null ? '; domain=' + domain : '';
cookieSecure = secure != null ? '; secure' : '';
document.cookie = this._cookieNamePrefix + name + '=' + escape(value) + cookieExpire + cookiePath + cookieDomain + cookieSecure;
};
UtmCookie.prototype.readCookie = function(name) {
var c, ca, i, nameEQ;
nameEQ = this._cookieNamePrefix + name + '=';
ca = document.cookie.split(';');
i = 0;
while (i < ca.length) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
i++;
}
return null;
};
UtmCookie.prototype.eraseCookie = function(name) {
this.createCookie(name, '', -1, null, this._domain);
};
UtmCookie.prototype.getParameterByName = function(name) {
var regex, regexS, results;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
regexS = '[\\?&]' + name + '=([^&#]*)';
regex = new RegExp(regexS);
results = regex.exec(window.location.search);
if (results) {
return decodeURIComponent(results[1].replace(/\+/g, ' '));
} else {
return '';
}
};
UtmCookie.prototype.additionalParamsPresentInUrl = function() {
var j, len, param, ref;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.utmPresentInUrl = function() {
var j, len, param, ref;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.writeCookie = function(name, value) {
this.createCookie(name, value, this._cookieExpiryDays, null, this._domain);
};
UtmCookie.prototype.writeAdditionalParams = function() {
var j, len, param, ref, value;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeUtmCookieFromParams = function() {
var j, len, param, ref, value;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeCookieOnce = function(name, value) {
var existingValue;
existingValue = this.readCookie(name);
if (!existingValue) {
this.writeCookie(name, value);
}
};
UtmCookie.prototype._sameDomainReferrer = function(referrer) {
var hostname;
hostname = document.location.hostname;
return referrer.indexOf(this._domain) > -1 || referrer.indexOf(hostname) > -1;
};
UtmCookie.prototype._isInvalidReferrer = function(referrer) {
return referrer === '' || referrer === void 0;
};
UtmCookie.prototype.writeInitialReferrer = function() {
var value;
value = document.referrer;
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookieOnce('referrer', value);
};
UtmCookie.prototype.writeLastReferrer = function() {
var value;
value = document.referrer;
if (!this._sameDomainReferrer(value)) {
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookie('last_referrer', value);
}
};
UtmCookie.prototype.writeInitialLandingPageUrl = function() {
var value;
value = this.cleanUrl();
if (value) {
this.writeCookieOnce('initial_landing_page', value);
}
};
UtmCookie.prototype.initialReferrer = function() {
return this.readCookie('referrer');
};
UtmCookie.prototype.lastReferrer = function() {
return this.readCookie('last_referrer');
};
UtmCookie.prototype.initialLandingPageUrl = function() {
return this.readCookie('initial_landing_page');
};
UtmCookie.prototype.incrementVisitCount = function() {
var cookieName, existingValue, newValue;
cookieName = 'visits';
existingValue = parseInt(this.readCookie(cookieName), 10);
newValue = 1;
if (isNaN(existingValue)) {
newValue = 1;
} else {
newValue = existingValue + 1;
}
this.writeCookie(cookieName, newValue);
};
UtmCookie.prototype.visits = function() {
return this.readCookie('visits');
};
UtmCookie.prototype.setCurrentSession = function() {
var cookieName, existingValue;
cookieName = 'current_session';
existingValue = this.readCookie(cookieName);
if (!existingValue) {
this.createCookie(cookieName, 'true', this._sessionLength / 24, null, this._domain);
this.incrementVisitCount();
}
};
UtmCookie.prototype.cleanUrl = function() {
var cleanSearch;
cleanSearch = window.location.search.replace(/utm_[^&]+&?/g, '').replace(/&$/, '').replace(/^\?$/, '');
return window.location.origin + window.location.pathname + cleanSearch + window.location.hash;
};
return UtmCookie;
})();
var UtmForm, _uf;
UtmForm = (function() {
function UtmForm(options) {
if (options == null) {
options = {};
}
this._utmParamsMap = {};
this._utmParamsMap.utm_source = options.utm_source_field || 'USOURCE';
this._utmParamsMap.utm_medium = options.utm_medium_field || 'UMEDIUM';
this._utmParamsMap.utm_campaign = options.utm_campaign_field || 'UCAMPAIGN';
this._utmParamsMap.utm_content = options.utm_content_field || 'UCONTENT';
this._utmParamsMap.utm_term = options.utm_term_field || 'UTERM';
this._additionalParamsMap = options.additional_params_map || {};
this._initialReferrerField = options.initial_referrer_field || 'IREFERRER';
this._lastReferrerField = options.last_referrer_field || 'LREFERRER';
this._initialLandingPageField = options.initial_landing_page_field || 'ILANDPAGE';
this._visitsField = options.visits_field || 'VISITS';
this._addToForm = options.add_to_form || 'all';
this._formQuerySelector = options.form_query_selector || 'form';
this.utmCookie = new UtmCookie({
domain: options.domain,
sessionLength: options.sessionLength,
cookieExpiryDays: options.cookieExpiryDays,
additionalParams: Object.getOwnPropertyNames(this._additionalParamsMap)
});
if (this._addToForm !== 'none') {
this.addAllFields();
}
}
UtmForm.prototype.addAllFields = function() {
var fieldName, param, ref, ref1;
ref = this._utmParamsMap;
for (param in ref) {
fieldName = ref[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
ref1 = this._additionalParamsMap;
for (param in ref1) {
fieldName = ref1[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
this.addFormElem(this._initialReferrerField, this.utmCookie.initialReferrer());
this.addFormElem(this._lastReferrerField, this.utmCookie.lastReferrer());
this.addFormElem(this._initialLandingPageField, this.utmCookie.initialLandingPageUrl());
this.addFormElem(this._visitsField, this.utmCookie.visits());
};
UtmForm.prototype.addFormElem = function(fieldName, fieldValue) {
var allForms, firstForm, form, i, len;
if (fieldValue) {
allForms = document.querySelectorAll(this._formQuerySelector);
if (allForms.length > 0) {
if (this._addToForm === 'first') {
firstForm = allForms[0];
firstForm.insertBefore(this.getFieldEl(fieldName, fieldValue), firstForm.firstChild);
} else {
for (i = 0, len = allForms.length; i < len; i++) {
form = allForms[i];
form.insertBefore(this.getFieldEl(fieldName, fieldValue), form.firstChild);
}
}
}
}
};
UtmForm.prototype.getFieldEl = function(fieldName, fieldValue) {
var fieldEl;
fieldEl = document.createElement('input');
fieldEl.type = "hidden";
fieldEl.name = fieldName;
fieldEl.value = fieldValue;
return fieldEl;
};
return UtmForm;
})();
_uf = window._uf || {};
window.UtmForm = new UtmForm(_uf);
/*
var USOURCE = jQuery("input[name='USOURCE']").val();
var UMEDIUM = jQuery("input[name='UMEDIUM']").val();
var UCAMPAIGN = jQuery("input[name='UCAMPAIGN']").val();
var UCONTENT = jQuery("input[name='UCONTENT']").val();
var UTERM = jQuery("input[name='UTERM']").val();
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
console.log(USOURCE);
console.log(UMEDIUM);
console.log(UCAMPAIGN);
console.log(VISITS);
*/
jQuery('#saveProfile').on('click', function(e){
console.log('Click submitted');
e.preventDefault();
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var readCampaign = readCookie_uc_utm_campaign
var FirstName = jQuery('#ownerInformation_FirstName').val();
var LastName = jQuery('#ownerInformation_LastName').val();
var USOURCE = getCookie('_uc_utm_source');
console.log(USOURCE);
var UMEDIUM = getCookie('_uc_utm_medium') || '';
var UCAMPAIGN = getCookie('_uc_utm_campaign') || '';
var UCONTENT = getCookie('_uc_utm_content') || '';
var UTERM = getCookie('_uc_utm_term') || '';
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
dataLayer.push({'event':FirstName,'event_cat':LastName,'event_action':USOURCE,'event_label':VISITS});
jQuery.ajax({
url: "https://script.google.com/macros/s/googleappsscript/exec",
data: {'FirstName':FirstName,'LastName':LastName,'USOURCE':USOURCE, 'UMEDIUM':UMEDIUM, 'UCAMPAIGN':UCAMPAIGN, 'UCONTENT':UCONTENT, 'UTERM':UTERM, 'IREFERRER':IREFERRER, 'LREFERRER':LREFERRER, 'VISITS':VISITS},
type: "POST",
dataType: "json"
});
});
})
</script>
Any help or guidance would be greatly appreciated.
Thanks,
Blaine
The reason why cookies are restricted by domains like this is to prevent security breaches.
See this answer for the way around it: Cross-Domain Cookies
I am coding a template for eBay. However, eBay does not allow .replace. The code below is for a rollover tab section.When the user hovers over tab(a), the correspodning div div(a) is made to become visible.
Is there a workaround to get the code to work without using .replace?
var divs = new Array();
divs.push("contentPayment");
divs.push("contentShipping");
divs.push("contentWarranty");
divs.push("contentContact");
var navs = new Array();
navs.push("nav1");
navs.push("nav2");
navs.push("nav3");
navs.push("nav4");
///////////////////////////////////////
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
///////////////////////////////////////////////////////////////////////
function toggleDisplay(id) {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = 'none';
}
var target = document.getElementById(id);
target.style.display = 'block';
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////PAYMENT IS HOVERED////////////////////////////////////////////////////////
if (id == "contentPayment") {
var CurrentTab = document.getElementById("nav1");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Shipping IS HOVERED////////////////////////////////////////////////////////
if (id == "contentShipping") {
var CurrentTab = document.getElementById("nav2");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Warranty IS HOVERED////////////////////////////////////////////////////////
if (id == "contentWarranty") {
var CurrentTab = document.getElementById("nav3");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Contact IS HOVERED////////////////////////////////////////////////////////
if (id == "contentContact") {
var CurrentTab = document.getElementById("nav4");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
}
You may try this as an alternative of replace function
String.prototype.fakeReplace = function(str, newstr) {
return this.split(str).join(newstr);
};
var str = "Welcome javascript";
str = str.fakeReplace('javascript', '');
alert(str); // Welcome
DEMO.
For a more efficient, but slightly longer method, use this:
String.prototype.myReplace = function(pattern, nw) {
var curidx = 0, len = this.length, patlen = pattern.length, res = "";
while(curidx < len) {
var nwidx = this.indexOf(pattern, curidx);
console.log(nwidx);
if(nwidx == -1) {
break;
}
res = res + this.substr(curidx, nwidx - curidx);
res = res + nw;
curidx = nwidx + patlen;
}
return res;
};
alert("Glee is awesome".myReplace("awesome", "very very very awesome"));
See it in action: little link.
Hope that helped!