I am trying to create tabs with listviews in JQM dynamically on a button click. Currently, I use JS array that contains sample data which will finally be populated via ajax. After research, it seems that I should trigger either trigger("create") or trigger ("refresh"), but apparently, I don't do it correctly. Here's the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>navbar demo</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" src="../JS/nav.js"></script>
</head>
<body>
<button onclick="fillCategories()">Fill</button>
<div id = "decisions" > </div>
</body>
</html>
Javascript:
function fillCategories() {
var navElements = [{"category_sublist_id":"1","category_sublist_name":"Europe"},
{"category_sublist_id":"2","category_sublist_name":"Asia"},
{"category_sublist_id":"3","category_sublist_name":"Americas"}];
var categoriesTabs = $('<div id="categories">')
.attr("data-role","tabs")
.appendTo("#decisions");
var navBar = $("<div>").attr("id","categoriesNames")
.attr("data-role","navbar")
.appendTo("#categories");
var listElements = [{"sublist_row_id":"1","category_sublist_id":"1","sublist_name":"Great Britain"},
{"sublist_row_id":"2","category_sublist_id":"1","sublist_name":"Sweden"},
{"sublist_row_id":"3","category_sublist_id":"1","sublist_name":"France"},
{"sublist_row_id":"4","category_sublist_id":"1","sublist_name":"Germany"}];
$("#categoriesNames").append($("<ul>").attr("id","categoriesUl"));
$(navElements).each(function(){
$("#categoriesUl").append($("<li>")
.attr("value", this.category_sublist_id)
.append($("<a>")
.attr("href", "#sublist"+this.category_sublist_id)
.attr("data-theme","a")
.attr("data-ajax","false")
.text(this.category_sublist_name)));
});
$("#categories").append(navBar).trigger("create");
categorySublistView("categories", "sublist2", listElements);}
function categorySublistView(elementId, listLink, listData) {
var listId = listLink+"id";
var tab = $("<div>").attr("id",listLink)
.addClass("ui-content")
.appendTo("#"+elementId);
var list = $("<ul>").attr("data-role","listview")
.attr("data-inset","true")
.attr("data-icon","false")
.attr("id", listId)
.appendTo("#"+listLink);
$(listData).each(function(){
var li = $("<li/>")
.attr("value",this.sublist_row_id)
.appendTo("#"+listId);
var link =$("<a>")
.attr("href", "#")
.text(this.sublist_name)
.appendTo(li);
});
if ( $('#'+listId).hasClass('ui-listview')) {
$('#'+listId).listview('refresh');
}
else {
$('#'+listId).trigger('create');
}}
edit:
My initial intention was to draw 3 tabs in the navbar which are listviews, which are visible on tab clicks
Related
I am attempting to change the backgroundColor of "gridElement" once "button" is clicked.
What was attempted, changing the way the elements are created to later include the event:
cloneNode() // doesn't work with eventListeners unless you use eventDelegation, in this case there is no parentElement to delegate the event too.
jQuery.clone() // the event is not tied directly to "gridElement" rather it is tied to "button" so jQuery.clone() would not be deep copying any associated events.
Also, attempting to make references to all gridElements:
used window.globalVarRef = localVar. // only references the first element and not all.
How can I modify the code so that the eventListener will change all "gridElement" and not just the first?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
window.allGridElements.style.backgroundColor = 'blue';
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
The problem lies in your changeBkg function. To select all of the elements with the class of "gridElement", you want to use a for loop to find those elements and then change their styles. I added some basic css to the grid element so we can see the color change in action. Does that solve your issue?
.gridElement {
width: 100px;
height: 100px;
background: red;
display: inline-block;
margin-right: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
var items = document.getElementsByClassName('gridElement');
for (let i=0; i < items.length; i++) {
items[i].style.backgroundColor = 'blue';
}
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href = "style.css">
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) acceptCommand();
setInterval(scrollUpdate, 1000);
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}
After the use button is clicked, the sources when I inspect the page show that the style.css page goes away, and no styles are applied. I can't figure out why this is happening.
My index.html page looks like this:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;500&family=Roboto:wght#100;300;400;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="First name" class="fname">
<input type="submit" value="Use" class="submit">
<script src="app.js"></script>
</body>
</html>
And my app.js is this:
const useBtn = document.querySelector('.submit');
const reloadBtn = document.querySelector('.btn__reload')
document.body.style.fontFamily = "Roboto;"
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
document.write(`<h2>It's ${person}'s turn!</h2>`)
document.write(`<h4>How long will they live?</h4>`)
let oldAge = `<p>${Math.floor((Math.random() * 10)+ 30)}</p>`
document.write(oldAge)
document.write(`<h4>What will be their yearly salary?</h4>`)
let salary = `<p>${Math.floor(Math.random() * 10000)}</p>`
document.write(salary)
document.write(`<h4>What will be their career</h4>`)
const jobs = [ 'plumber', 'doctor', 'witch', 'president', 'trump supporter']
let job = Math.floor(Math.random() * jobs.length)
document.write(jobs[job])
redoBtn();
})
function redoBtn(){
let tryAgain = document.createElement('button')
document.body.appendChild(tryAgain)
let buttonText = document.createTextNode('Try Again')
tryAgain.appendChild(buttonText)
tryAgain.addEventListener('click', function(){
window.location.href = window.location.href;
})
}
Any help is so appreciated!
Your document.write is overwriting all your html, including your linked stylesheet.
From https://developer.mozilla.org/en-US/docs/Web/API/Document/write:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
If you really want to use document.write, you'll need to rewrite your stylesheet link into the new document. But it might be better to just replace the html of some container element on your page, like the body element.
Instead of using document.write which overwrites your html you could try this approach:
<input type="submit" value="Use" class="submit">
<!-- add new div to show the result -->
<div id="result"></div>
<script src="app.js"></script>
And in the click event:
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
let res = document.getElementById('result');
res.innerHTML = "<h2>It's "+person+"'s turn!</h2>";
// add further information to innerHTML here
// hide input fname and submit button
redoBtn();
})
So i'm trying to make a realtime button using Javascript and Firebase. Currently I have a working button which is changing the variable in the realtime database from on to off. But the default value isn't saved so when I switch the button off and reload the page it shows that it is on how can I fix this? I also want it to be updated realtime between all the clients
App.js
(function() {
//Get elements
const preObject = document.getElementById('object');
// Create reference
dbRefObject = firebase.database().ref().child('button').child('value')
// Sync changes
dbRefObject.on('value', snap => console.log(snap.val()));
}());
document.addEventListener("DOMContentLoaded", function() {
console.log("test");
});
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
const dbRefObject = firebase.database().ref().child('button')
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
dbRefObject.set({value: true})
console.log('Checked');
} else {
dbRefObject.set({value: false})
console.log('Not checked');
}
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://www.gstatic.com/firebasejs/live/3.1/firebase.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox" id="checkbox" checked>
<div class="slider"></div>
</label>
<script src="app.js"></script>
</body>
</html>
You're reading the data from the database, but not doing anything useful with it yet here:
dbRefObject.on('value', snap => console.log(snap.val()));}
To have the button reflect the state that you store in the database, use this listener to update the button's state:
dbRefObject.on('value', (snap) {
var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.checked = snap.val().value;
})
I want to create a new div element, with unique id from the latest array that i push every i click a create button , but it seem my code not working, here is my code below :
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
$('.container').append('<div class="image">hallo</div');
counter ++;
arr.push(counter);
$('.image').attr('id',arr[arr.length-1]);
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>
On each click you are setting id of each image element to last element in array, instead you can do something like this.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $('<div />', {
'class': 'image',
'id': arr.slice(-1)
}).text('hallo');
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
Or you can first push counter to array and then take last element for array with slice and use it as id.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $(`<div class="image" id=${arr.slice(-1)}>hallo</div>`)
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
First when you use classe query selector it would add the id to every element with that class so here is a work around you can use :
Add the add on the appending part
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
counter ++;
arr.push(counter);
$('.container').append('<div id='+(arr.length-1)+' class="image">hallo '+(arr.length-1)+'</div');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>
Your original code is selecting all div with the image class and updating them all with the latest number.
I suggest creating the div adding the number to the new div only and then appending it to the container.
Please review the updated code below:
$(document).ready(function() {
var arr = [];
counter = 0;
$('#newDiv').on('click', function() {
counter++;
arr.push(counter);
// Create div
$('<div class="image"></div').text('hallo')
// Add ID attribute
.attr('id', arr[arr.length - 1])
// Apend new div to container
.appendTo('.container');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>