How to detect joy-con input/motion controls in HTML5 JavaScript - javascript

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.

Related

Converting rTabs from bs3 to bs5

I want to make something awesome for Bootstrap 5.
As I search for week now, there aren't many good Tabs-responsive tabs solutions for Bootstrap 5 and most of them are not really good solution for mobile phones.
But in my search I encountered this one: https://codepen.io/Ayn_/pen/xdVBVg
https://github.com/Aynn/Bootstrap-Responsive-Tabs
So far my try with bs5: https://codepen.io/xkpx/pen/ExWXKRy
How can I convert this to work with bs5?
$(document).ready(function() {
rTab();
});
$(window).resize(function() {
rTab_resize();
});
function rTab()
{
$('.nav-tabs').each(function() {
var li = [];
var le = [];
var ddtab_w;
var currentw = $(this).outerWidth();
for(var i = 0; i < $(this)[0].children.length; i++)
{
li.push($(this)[0].children[i].outerHTML);
le.push($(this)[0].children[i].offsetWidth);
if(i == $(this)[0].children.length-1)
{
//$(this)[0].children[i].innerHTML = "<a href='#' data-toggle='tab'> Tab ("+ (i+1) +") <span class='caret'></span></a></a>";
ddtab_w = $(this)[0].children[i].offsetWidth;
}
}
var total_tabs = $(this)[0].children.length;
var wTracker = 0;
var tabs;
$(this).html('');
for(var i = 0; i < li.length; i++)
{
if((le[i] + wTracker) <= currentw)
{
wTracker += le[i];
tabs = i;
if (i == li.length-1)
{
for(var i = 0; i < li.length; i++)
{
$(this).append(li[i]);
}
}
} else {
i = li.length-1;
while(ddtab_w + wTracker >= currentw)
{
wTracker -= le[tabs--];
}
if(tabs < 0) { tabs = 0; }
for(var x = 0; x < tabs; x++)
{
$(this).append(li[x]);
}
var dropdown_tabs = ddTab(total_tabs-tabs, "Tabs");
$(this)[0].appendChild(dropdown_tabs[0]);
wTracker += $(this)[0].children[$(this)[0].children.length-1].offsetWidth;
while(tabs<li.length)
{
dropdown_tabs[1].innerHTML += li[tabs++];
}
}
}
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
isActive(dropdown_tabs, $(this)[0].children[$(this)[0].children.length-1]);
}
if($(this)[0].children.length == 1)
{
dropdown_tabs[0].style.paddingLeft = "10px";
dropdown_tabs[0].style.marginRight = "-10px";
dropdown_tabs[0].style.textAlign = "center";
dropdown_tabs[0].style.position = "relative";
dropdown_tabs[0].style.width = "100%";
dropdown_tabs[0].setAttribute("class","dropdown pull-right active");
dropdown_tabs[1].style.left = "7px";
dropdown_tabs[2].data = dropdown_tabs[1].children[0].innerText + " (" + dropdown_tabs[1].children.length + ")";
$(dropdown_tabs[1]).click(function() {
dropdown_tabs[2].data =event.target.text + " (" + dropdown_tabs[1].children.length + ")";
});
}
});
}
function rTab_resize()
{
reset();
rTab();
}
function reset()
{
$('.nav-tabs').each(function() {
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
var drop_down_tab = $(this)[0].children[$(this)[0].children.length-1].children[1];
var initial_value = drop_down_tab.children.length;
for(var i = 0; i < initial_value; i++)
{
$(this).append(drop_down_tab.children[0]);
}
$(this)[0].children[$(this)[0].children.length-(1+initial_value)].remove();
}
});
}
function ddTab(total_dropdown, tabName)
{
var n_li = document.createElement("li");
n_li.setAttribute("class","dropdown pull-right");
n_li.style.position = "relative";
n_li.style.right = "13px";
var n_a = document.createElement("a");
n_a.setAttribute("class","dropdown-toggle");
n_a.setAttribute("data-toggle","dropdown");
n_a.setAttribute("href","#");
var n_sp = document.createElement("span");
n_sp.setAttribute("class","caret");
var n_ul = document.createElement("ul");
n_ul.setAttribute("class","dropdown-menu");
var n_tx = document.createTextNode(tabName + " (" + total_dropdown + ")");
n_a.appendChild(n_tx);
n_a.appendChild(n_sp);
n_li.appendChild(n_a);
n_li.appendChild(n_ul);
return [n_li, n_ul, n_tx];
}
function isActive(dropdown_tabs, child)
{
for (var i = 0; i < dropdown_tabs[1].children.length; i++)
{
if(dropdown_tabs[1].children[i].classList[0] == "active")
{
child.setAttribute("class","dropdown pull-right active");
}
}
}

HtmlOptions.OnLoadScript doesnt works to create PDF with ABCPdf

I have a html page created with bootstrap, and i want to create a PDF with it and for this i'm using ABCPdf.
I'm trying to execute a javascript script to apply some styles to my html, but it doesn't works. Someone knows what happens?
Doc theDoc = new Doc();
theDoc.Rect.Inset(5, 20);
theDoc.HtmlOptions.Timeout = 3000000;
theDoc.HtmlOptions.UseScript = true;
theDoc.HtmlOptions.PageCacheEnabled = false;
theDoc.HtmlOptions.DoMarkup = true;
theDoc.HtmlOptions.HostWebBrowser = false;
theDoc.HtmlOptions.Media = MediaType.Screen;
theDoc.HtmlOptions.BrowserWidth = 1500;
theDoc.HtmlOptions.AddLinks = true;
string script = #"var elemento = document.getElementById('description');"
+"for (i = 0; i < elemento.childNodes.length; i++) {"
+ "if (elemento.childNodes[i].className == 'row') {"
+ " if (elemento.childNodes[i].offsetHeight > 200) {"
+ "elemento.childNodes[i].className += ' saltoPagina'; } } }";
theDoc.HtmlOptions.OnLoadScript = script;
int theID;
theID = theDoc.AddImageUrl(url, true, 0, true);
Thanks in advance. :)
Solve: If you are using ABCPdf, you cant execute javaScript (jQuery never works) without the next line:
theDoc.HtmlOptions.Engine = EngineType.Gecko;
And then executes your code:
theDoc.HtmlOptions.GeckoSubset.OnLoadScript =
#"(function() {
window.ABCpdf_go = false;
var elemento = document.getElementById('description');
var elementos = elemento.childNodes;
var contador = 0;
for (i = 0; i < elementos.length; i++) {
if(elementos[i].className == 'info'){
contador = contador + elementos[i].offsetHeight;
if(contador > 1600) {
contador = elementos[i].offsetHeight;
var childElements = elementos[i].childNodes;
for(j = 0; j < childElements.length; j++) {
if (childElements[j].className == 'infoDescrip' && i != 1){
childElements[j].className += ' saltoPagina';
}
}
}
}
}
window.ABCpdf_go = true;
})();";
But if you use EngineType.Gecko, bootstrap librarie doesn't works.

Crossfading with a single img

I'm trying to make a cross fade inside a bootstrap grid duplicating the images.
The problem is the images don't stack over each other and it sometimes creates new images - however it doesn't delete them.
var tempo1 = setInterval(rand, 6000);
function rand() {
var imagensTroca = 5;
var grupos = [
['DFLO_0005', 'DFLO_0030', 'DFLO_0042', 'DFLO_0068', 'DFLO_0084'],
['DANI_0004', 'DANI_0012', 'DANI_0020', 'DANI_0027'],
['DCAV_0003', 'DCAV_0017', 'DCAV_0024'],
['DCOR_0029', 'DCOR_0010', 'DCOR_0001'],
['DETI_0004', 'DETI_0002', 'DETI_0007'],
['DGEO_0002', 'DGEO_0009', 'DGEO_0001'],
['DIND_0001', 'DIND_0006', 'DIND_0012'],
['DOLD_0001', 'DOLD_0002', 'DOLD_0008'],
['DPSI_0006', 'DPSI_0008', 'DPSI_0013'],
['DUNI_0025', 'DUNI_0031', 'DUNI_0032'],
['DVIN_0002', 'DVIN_0014', 'DVIN_0016'],
['DXAD_0001', 'DXAD_0002', 'DXAD_0014'],
['DFRA_0004', 'DFRA_0006', 'DFRA_0007'],
['DOLH_0002', 'DOLH_0003', 'DOLH_0004'],
['DYIN_0011', 'DYIN_0005', 'DYIN_0009']
];
var dCheck = [];
for (i = 0; i < imagensTroca; i++) {
var parteDoArray = Math.floor(Math.random() * grupos.length);
var divisaoDoArray = grupos[parteDoArray].toString();
var selecaoDaDivisao = divisaoDoArray.split(",");
var imagemEscolhida = selecaoDaDivisao[Math.floor(Math.random() * selecaoDaDivisao.length)];
var img = document.getElementById('cat' + parteDoArray);
var cacheDaImagem = img.src;
if (dCheck[0] != parteDoArray) {
var newImg = new Image();
newImg.src = cacheDaImagem;
$('#box' + parteDoArray).append(newImg);
newImg.id = "clone" + parteDoArray.toString();
newImg.className += "img-circle img-clone";
dCheck[0] = parteDoArray;
change1(imagemEscolhida, parteDoArray);
}
}
}
function change1(_loc1, _loc2) {
$(document).ready(function() {
var img2 = document.getElementById('cat' + _loc2);
img2.src = 'http://www.alargs.com/themes/theshop/img/jumbotron/' + _loc1 + '.jpg';
img2.hide();
$('#clone' + _loc2).stop(true).fadeOut(1000, function() {
$(this).remove();
});
$('#cat' + _loc2).fadeIn(1000);
});
}
https://jsfiddle.net/f8xaey4t/
I researched by myself and made it so if someone else need it it's here:
var tempo1 = setInterval(rand,3000);
function rand() {
var imagensTroca = 6;
var grupos = [['DFLO_0005','DFLO_0030','DFLO_0042','DFLO_0068','DFLO_0084'],['DANI_0004','DANI_0012','DANI_0020','DANI_0027'],['DCAV_0003','DCAV_0017','DCAV_0024'],['DCOR_0029','DCOR_0010','DCOR_0001'],['DETI_0004','DETI_0002','DETI_0007'],['DGEO_0002','DGEO_0009','DGEO_0001'],['DIND_0001','DIND_0006','DIND_0012'],['DOLD_0001','DOLD_0002','DOLD_0008'],['DPSI_0006','DPSI_0008','DPSI_0013'],['DUNI_0025','DUNI_0031','DUNI_0032'],['DVIN_0002','DVIN_0014','DVIN_0016'],['DXAD_0001','DXAD_0002','DXAD_0014'],['DFRA_0004','DFRA_0006','DFRA_0007'],['DOLH_0002','DOLH_0003','DOLH_0004'],['DYIN_0011','DYIN_0005','DYIN_0009']];
var dCheck = [];
var dCheck2 = [];
for( i=0; i < imagensTroca; i++){
var parteDoArray = Math.floor(Math.random() * grupos.length);
var divisaoDoArray = grupos[parteDoArray].toString();
var selecaoDaDivisao = divisaoDoArray.split(",");
var imagemEscolhida = selecaoDaDivisao[Math.floor(Math.random() * selecaoDaDivisao.length)];
var img = document.getElementById('cat' + parteDoArray);
var cacheDaImagem = img.src;
if(check(dCheck,imagemEscolhida)===true && check(dCheck2,parteDoArray)===true){
var newImg = new Image();
newImg.src = cacheDaImagem;
$('#box'+parteDoArray).append(newImg);
newImg.id = "clone"+parteDoArray;
newImg.className += "img-circle img-clone";
dCheck[i] = imagemEscolhida;
dCheck2[i] = parteDoArray;
change1(imagemEscolhida,parteDoArray);
$('#clone'+parteDoArray).fadeOut(1000,function() { for( k=0; k<= grupos.length; k++){ $('#clone'+k).remove();}});
$('#cat'+parteDoArray).fadeIn(1000);
}
}
}
function change1(_loc1,_loc2){
$(document).ready(function () {
var img2 = document.getElementById('cat'+_loc2);
img2.src = 'themes/theshop/img/jumbotron/' + _loc1 + '.jpg';
});
}
function check(arr,test) {
var i;
for (i = 0; i <= arr.length; i++) {
if (arr[i] === test) {
return false;
}
}

Can't validate this! Validation process keeps stopping

I'm having problems validating this piece of javascript code. JSlint keeps stopping after the first for instruction and I can't seem to figure out why. It seems as if the validator is picking on warnings rather than errors (such as "use space instead of tabs" or "expected +=1 instead of ++" which all seem fine to me). Also, I'm not sure if it does what it's supposed to but I can't check that until I get the validation done.
var prompt = document.getElementById("prompt");
var response = document.getElementById("response");
var warning = document.getElementById("warning");
var fixation = 'fixPlus.jpg';
var cueImage = ['fixPlus.jpg', 'midCue.jpg', 'bothCue.jpg', 'topCue.jpg', 'botCue.jpg'];
//images for stimuli were taken from wheedesign.com
var stImage = ['T_L_N.jpg', 'T_L_C.jpg', 'T_L_I.jpg', 'T_R_N.jpg', 'T_R_C.jpg', 'T_R_I.jpg', 'B_L_N.jpg', 'B_L_C.jpg', 'B_L_I.jpg', 'B_R_N.jpg', 'B_R_C.jpg', 'B_R_I.jpg'];
var condIdx[1];
var i;
for (i = 2, i <= 47; i++) {
condIdx.push(i);
}
var cueType = ['0', '1', '2']; //I will use a repetitive instruction instead of writing 000,111, etc
for (i = 0; i < 11; i++) {
cuetype[i] = 0;
}
for (i = 12; i < 23; i++) {
cueType[i] = 1;
}
for (i = 24; i < 35; i++) {
cueType[i] = 2;
}
for (i = 36; i < 41; i++) {
cueType[i] = 3;
}
for (i = 42; i < 47; i++) {
cueType[i] = 4;
}
var stType = ['0', '1', '2', '3', '4', '5', '6', '7'];
var ansKey = ['Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'M', 'M', 'M', 'M', 'M', 'M'];
var promptTxt = 'Press Z for left and M for right';
var invalidTxt = ' -- Invalid key press!!!';
var correctTxt = 'correct answer!';
var incorrectTxt = 'incorrect answer!'
var waitTxt = 'Wait for the prompt!';
var tooSlow = 'Too slow!';
var toa = 400; //trial onset asynchrony in ms
var preCueFixTime[500, 600, 700, 800, 900, 1000, 1100, 1200]; //pre-cue fixation
var cueTime = 100; // cue in ms
var postCueTime = 400; //post-cue fixation
var maxStTime = 1500; //stimulus display (until a key is pressed or 1500ms has lapsed)
var promptTime = 1500; // duration of response prompt in ms
var nTrial = isPractice ? 1 : 24;
var trialCounter = 0; //to keep track of progress
var remainStr = ''; //remaining trials
var doneStr = ''; //trials completed
var indxChar = '='; //character used to indicate a trial
var remainColor = 'LightBlue'; //color to display remainStr
var doneColor = 'Navy';
var progTxt = 'Progress: '.fontcolor(doneColor);
var rspArr = []; //to store responses
var cssFile = '<link rel = "stylesheet" type = "text/css" href = "rngStyle.css">';
var blocks = 0;
function block_initiation() {
if (blocks < 7) {
warning.innerHTML = '';
response.innerHTML = '';
object.onclick = "trialBlock()" + 'Click here to begin a block of trials!';
blocks++;
updateProgress();
} else {
submitData();
}
}
function trialBlock() {
"use strict";
condIdx = shuffle(condIdx);
preCueFixTime = shuffle(preCueFixTime);
cueImage = shuffle(cueImage);
for (i = 0; i < 6; i++) {
var theTask = setInterval(function () {
aTrial();
}, toa);
}
}
function aTrial() {
"use strict";
if (trialCounter < nTrial) {
warning.innerHTML = '';
response.innerHTML = '';
getKeypress();
trialCounter++;
updateProgress();
} else {
submitData();
}
}
function getKeypress() {
"use strict";
rspArr.push(0);
// fixation - cue - fixation - stimulus - key press/too slow
var interval = window.setInterval(function () {
if (fixation.display == 'hidden') {
fixation.style.visibility = 'visible';
} else {
fixation.style.visibility = 'hidden';
}
}, preCueFixTime[trialCounter]); //display initial fixation
if (cueImage[trialCounter].display == 'hidden') {
cueImage[trialCounter].style.visibility = 'visible';
} else {
cueImage[trialCounter].style.visibility = 'hidden';
}
}, 100); //shows cue display for 100ms
prompt.innerHTML = promptTxt; //show the prompt text
setTimeout(function () {
prompt.innerHTML = '';
}, promptTime);
if (stImage[condIdx[trialCounter]].display == 'hidden') {
stImage[condIdx[trialCounter].style.visibility = 'visible';
} else {
stImage[condIdx[trialCounter]].style.visibility = 'hidden';
}
}, 1500);
setTimeout(function () {
tooSlow.innerHTML = '';
}, tooSlow);
var inputRecorded = false;
document.onkeydown = function (e) {
if (inputRecorded) {
warning.innerHTML = waitTxt;
cueImage[trialCounter].style.visibility = 'hidden';
return false; //to cancel the event
}
e = e || window.event;
var key_press = String.fromCharCode(e.keyCode);
var regex = /[MZ]/;
condIdx[trialCounter].innerHTML = '';
//stImage[indeces 1 to 6] should be Z and stImage[7-12] should be M
var stStart = new Date();
fixation + cueImage[trialCounter] + fixation + stImage[condIdx[trialCounter]];
setTimeout(function () {
fixation.innerHTML = '';
}, preCueFixTime[trialCounter]); //this will still show preCueFixTime in ascending order
if (key_press.search(regex) > -1) {
var stEnd = new Date();
var RT = stEnd.getTime() - stStart.getTime();
//something was pressed
if (condIdx[trialCount] < 7 && key_press == 'Z'
OR condIdx[trialCount] >= 7 && key_press == 'M') {
//correct!
var correct = true;
trialCond = [cond Idx, cueType, correct, RT];
rspArr[trialCount] = trialCond.join();
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = correctTxt;
} else {
//incorrect!
var correct = false;
rspArr[rspArr.length - 1] = key_press;
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = incorrectTxt;
}
} else {
warning.innerHTML = key_press + invalidTxt;
}
inputRecorded = true;
}; //document.onkeydown
}
function updateProgress() {
"use strict";
//alert (trialCounter + ' ' + remainStr);
if (trialCounter === 0) {
for (var i = 0; i < nTrial; i++) {
remainStr += indxChar;
}
} else {
doneStr += indxChar;
remainStr = remainStr.slice(0, -1);
}
progress.innerHTML = progTxt + doneStr.fontcolor(doneColor) + remainStr.fontcolor(remainColor);
}
function checkProgress() {
"use strict";
var j, tot = 0,
n = rspArr.length;
//alert(tot + ' ' + n);
for (j = n - 5; j < n; j++) {
if (rspArr[j] > 0) {
tot++;
}
}
var actionAttr, fbkTxtm, valueAttr;
if (tot > 3) {
actionAttr = 'action="rng04Task.php"';
fbkTxt = '<h2>Good! That ends the practice. </h2>';
valueAttr = 'value="Click here to formally begin the task"';
} else {
actionAttr = 'action="rng03Practice.php"';
fbkTxt = '<h2>You are not quite in sync with the prompts </h2>' + '<h2> Please try again </h2>';
valueAttr = 'value="Click here to have some more practice"';
}
document.write(cssFile +
'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
//alert(cssFile +
//'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
}
function shuffle(arr) {
"use strict";
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return arr;
//function taken and adapted from http://jsfromhell.com/array/shuffle
};
function submitData() {
"use strict";
}
I suspect it's failing on:
var condIdx[1];
As I don't think that's valid js syntax. You are attempting to declare a variable name, and provide a size/or access an index, in the same line, without an equality statement?

Javascript .Replace Alternative

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!

Categories

Resources