Converting rTabs from bs3 to bs5 - javascript

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");
}
}
}

Related

Blogger random post display to prevent no posts infinite loop

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!

How to detect joy-con input/motion controls in HTML5 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.

Showing error Cannot read property 'style' of undefined

function InitMenu() {
var bar = menuBar.children
for (var i = 0; i < bar.length; i++) {
var menu = eval(bar[i].menu) menu.style.visibility = "hidden"
bar[i].onmouseover = new Function("ShowMenu(" + bar[i].id + ")") var Items = menu.children
for (var j = 0; j < Items.length; j++) {
var menuItem = eval(Items[j].id) if (menuItem.menu != null) {
menuItem.innerHTML += "<Span Id=" + menuItem.id + "_Arrow class='Arrow'>4</Span>" //var tmp = eval(menuItem.id+"_Arrow")
// tmp.style.pixelLeft = menu.getBoundingClientRect().Right //- tmp.offsetWidth - 15
FindSubMenu(menuItem.menu)
}
if (menuItem.cmd != null) {
menuItem.onclick = new Function("Do(" + menuItem.id + ")")
}
menuItem.onmouseover = new Function("highlight(" + Items[j].id + ")")
}
}
}
eval can only be used when the data is json object. I assume you have a menu within a div called "menuBar"
var menuBar=document.getElementById("menuBar");
function InitMenu() {
var bar = menuBar.childNodes;
for (var i = 0; i < bar.length; i++) {
var menu = bar[i];
menu.style.visibility = "hidden";
bar[i].onmouseover = new Function("ShowMenu(" + bar[i].id + ")") var Items = menu.children
for (var j = 0; j < Items.length; j++) {
var menuItem = eval(Items[j].id) if (menuItem.menu != null) {
menuItem.innerHTML += "<Span Id=" + menuItem.id + "_Arrow class='Arrow'>4</Span>" //var tmp = eval(menuItem.id+"_Arrow")
// tmp.style.pixelLeft = menu.getBoundingClientRect().Right //- tmp.offsetWidth - 15
FindSubMenu(menuItem.menu)
}
if (menuItem.cmd != null) {
menuItem.onclick = new Function("Do(" + menuItem.id + ")")
}
menuItem.onmouseover = new Function("highlight(" + Items[j].id + ")")
}
}
}

variable assignment doesn't work javascript

In the following code, the console.log from the line 92 and 93 (switchPosition function) doesn't provide the same result. I am, I have to admit, stuck.
Any thoughts, ideas, explanations?
Thanks you for the time taken,
var Carrousel = (function () {
var self = {},
config = {
item: 3, // item to be displayed
scroll: 2 // number of items to be scrolled
},
container = null,
items = null,
nbItems = null,
nbSlide = null,
position = [],
searchPositionDepending = []
;
self.init = function (opts) {
options = opts || {}
execute();
}
// Private Method
execute = function () {
container = document.getElementById('carrousel');
items = document.getElementsByClassName('flux');
var containerWidth = container.offsetWidth;
var containerHeight = items[0].offsetHeight * 1.5;
container.style.height = '' + containerHeight + '';
nbItems = document.getElementsByClassName('flux').length;
nbSlide = nbItems / config.item;
// Initialisation du Carrousel
for (i = 0; i < nbItems; i++) {
items[i].style.width = '' + (containerWidth / config.item) + '';
items[i].style.display = 'none';
items[i].style.position = 'absolute';
items[i].style.top = "0";
items[i].style.left = "0";
items[i].setAttribute('data-position', '' + (i + 1) + '');
items[i].setAttribute('data-number', '' + i + '');
}
searchPosition();
placement();
document.getElementById('next').onclick = function () {
next();
searchPosition();
switchPosition();
placement();
// position();
}
document.getElementById('previous').onclick = function () {
// previous();
// searchPosition();
// position();
}
}
searchPosition = function () {
for (i = 0; i < config.item; i++) {
searchPositionDepending[i] = (function () { //Appending a function searchPosition per item displayed
for (j = 1; j <= config.item; j++) { //Passing through the first items to get their position
if (items[i].dataset.position === '' + j + '') {
position[j] = items[i];
return true;
} else {
}
}
;
})();
}
}
switchPosition = function () {
for (i = 0, j = 0; i < nbItems; i++, j++) {
if (items[i].dataset.position === '' + j + '') {
position[i] = position[i];
}
}
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Replacing in good order, except for the one that are place into the variable position[];
items[i] = items[j];
}
for (i = (nbItems - config.item +1), j = 1; i <= nbItems; i++, j++) { //Replacing in good order the one that are place into variable position[];
items[i] = position[j];
console.log(i);
console.log(j);
console.log(position[j]);
console.log(items[i]);
}
for (i = 0; i < nbItems; i++) {
console.log(items[i]);
}
console.log(items[10]);
}
placement = function () {
for (i = 1; i <= config.item; i++) {
var rect = items[0].getBoundingClientRect();
item_width = Math.floor(rect.width);
item_height = Math.floor(rect.height);
var x = item_width * (i - 1) * 1.1;
items[i].style.display = 'block';
items[i].style.transform = "translate3D(" + x + "px, 0px, 0px)";
}
}
next = function () {
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Updating all dataset position, except for the items that are displayed.
items[i].dataset.position = j;
}
for (i = 1, j = 2; i <= config.item; i++, j--) {
position[i].dataset.position = nbItems - j;
position[i].style.display = "none";
}
}
return self;
})();

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