Dynamically map button with div - javascript

I want to link a button with div dynamically using id’s for example.
I have two buttons and two div this is been dynamically created if i click the second button it has to go second div if i click first button it first button has to visible. Using pure vanila javascript.
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
if(count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML=[1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML=[1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
prevPage.setAttribute('id', ['page' + (totalCount)]);
preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value="";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Kindly help me actually I am trying I am not getting it
Thanks in advance

I would suggest not using a partial id or anything like that to link your elements. Instead, use an attribute specifically created for the purpose. In the following code, I'm using an attribute named data-page which is simply set to the value you're appending to the ids. I also added an event handler which just sets the z-index of all pages to 0, then sets the selected page's z-index to 10.
//create div
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
.title_Textbox {
border: 1px solid rgb(152, 152, 152);
width: 230px;
padding: 5px 0 5px 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page">
</div>
<div id="pageBtn" class="row pagination_btn">
</div>

Related

Replacing values in a div

Been working on hangman using javascript and HTML, problem is whenever i click on a letter it doesn't replace the "_"
var myList=["Computer","Algorithm","Software","Programming","Developer"];
var n;
var star=" _";
console.log(myList)
computer=myList[Math.floor(Math.random() * myList.length)];
console.log(computer);
var word= document.getElementById("word").innerHTML=star.repeat(computer.length);
var letter=document.getElementsByClassName("col")
function myFunction(){
n=word.replace(star,letter);
};
for (var i=0; i<letter.length;i++){
letter[i].addEventListener("click",myFunction());
}
myFunction();
letter is basically alphabet(they are not buttons they are divs)
word is also an empty div in which the "-" goes in
in conclusion i want to replace word("-") with letters(which ever letter you click on)
Here is the working example:
var myList=["Computer","Algorithm","Software","Programming","Developer"];
var star="_";
var wrapper = document.querySelector('.wrapper');
for(var i = 0; i<myList.length; i++) {
var list = document.createElement('div');
list.setAttribute('class', 'wrapper-list');
list.setAttribute('id', 'list'+i);
wrapper.appendChild(list);
for(var j=0; j<myList[i].length;j++) {
var item = document.createElement('div');
item.setAttribute('class', 'wrapper-list__item');
item.innerText = myList[i][j];
list.appendChild(item);
item.onclick = function(e) {
this.innerText = star;
}
}
}
.wrapper .wrapper-list {
display: flex;
}
.wrapper .wrapper-list__item {
padding: 5px 10px;
border: 1px solid #dedede;
margin: 5px;
text-transform: uppercase;
cursor: pointer;
}
<div class="wrapper"></div>

Why does my button's style change when I click on it?

I edited my buttons' style, but when I click on one, a function is called and changes the value (via ajax, if that affects anything), but the button changes as on the image. This is my code:
$(document).ready(function() {
$(':button').on('click', function(event) {
$('#ID').val(this.id);
var tmp = this.id;
$.ajax({
type: $('#klik').attr("method"),
url: $('#klik').attr("action"),
data: $('#klik').serialize(),
success: function(d) {
alert(d)
$('#' + tmp).val(d);
const button = document.getElementById(tmp);
button.disabled = true;
if (d == 'bomba') {
alert('bb');
}
},
error: function() {
alert('Greska')
}
});
});
});
var docFrag = document.createDocumentFragment();
for (var i = 0; i < 9; i++) {
var row = document.createElement("tr")
for (var j = 0; j < 9; j++) {
var elem = document.createElement('input');
elem.className = 'gumb';
elem.type = 'button';
elem.id = 'r' + i + 's' + j;
elem.value = '';
elem.innerHTML = elem.value;
docFrag.appendChild(elem);
}
document.body.appendChild(docFrag);
document.body.appendChild(row);
}
This is my CSS:
.gumb {
width: 50px;
height: 50px;
background-color: blue;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
You need to align the text. Something like this:
.gumb {
vertical-align: middle;
}

Grid if box has specific class stop JavaScript

I have a grid with a player, yellow box, and obstacles (.ob) and black boxes. I don't want the player to go in the obstacle squares when I click the 'UP' button.
I was thinking to check if the next class has .ob do not go there. Any suggestions?
let moveCounter = 0;
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 50; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 20) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerTwo = [];
while (playerTwo.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerTwo.indexOf(randomIndex) === -1) {
playerTwo.push(randomIndex);
var drawPtwo = document.getElementById('square' + randomIndex);
$(drawPtwo).addClass("p-1")
}
};
$('#button_up').on('click', function() {
moveCounter += 1;
$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10
var idUpMove = 'square' + idMove;
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box > div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.p-1 {
background-color: yellow;
}
.ob {
background-color: black;
}
<div id="grid-box"></div>
<div class="move">
<button id="button_up">UP</button><br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
jsFifddle
Use the following code
$('#button_up').on('click', function() {
moveCounter += 1;
$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10
var idUpMove = 'square' + idMove;
if($('#' + idUpMove).hasClass('ob')){
return false;
}
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');
});
Here we check the next selected class having ".ob" class if its return true then we stop the process if it returns false then process continues
if($('#' + idUpMove).hasClass('ob')){
return false;
}
Fiddle

Remove form tags but maintain input functionality

I found a piece of code that works pretty close to how I want. The end result is that when you type something in the input field a list of relevant options appears below based on the text input. You can then click on one of these options instead of having to type of the full string.
The only problem is that when i try and adapt this code to my existing project it breaks because the input field is wrapped in a form. How would I modify this code so that it functions in the exact same way without having to wrap the input tag in a form element? I.e. just have an input field.
(
function()
{
var lookFor = [
"Paris",
"Canada",
"England",
"Scotland",
"Brazil",
"Manila",
"Atlanta"
];
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
// first, position the results:
var node = searchInput;
var x = 0;
var y = 0;
while ( node != null )
{
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
resultsDiv.style.left = x + "px";
resultsDiv.style.top = (y + 20) + "px";
// now, attach the keyup handler to the search field:
searchInput.onkeyup = function()
{
var txt = this.value.toLowerCase();
if ( txt.length == 0 ) return;
var txtRE = new RegExp( "(" + txt + ")", "ig" );
// now...do we have any matches?
var top = 0;
for ( var s = 0; s < lookFor.length; ++s )
{
var srch = lookFor[s];
if ( srch.toLowerCase().indexOf(txt) >= 0 )
{
srch = srch.replace( txtRE, "<span>$1</span>" );
var div = document.createElement("div");
div.innerHTML = srch;
div.onclick = function() {
searchInput.value = this.innerHTML.replace(/\<\/?span\>/ig,"");
resultsDiv.style.display = "none";
};
div.style.top = top + "px";
top += 20;
resultsDiv.appendChild(div);
resultsDiv.style.display = "block";
}
}
}
// and the keydown handler:
searchInput.onkeydown = function()
{
while ( resultsDiv.firstChild != null )
{
resultsDiv.removeChild( resultsDiv.firstChild );
}
resultsDiv.style.display = "none";
}
}
)();
.searchInput {
width: 200px;
}
#results {
display: none;
position: absolute;
width: 200px;
background-color: lightyellow;
z-index: 10;
}
#results div {
position: absolute;
width: 200px;
height: 20px;
background-color: white;
cursor: pointer;
overflow: hidden;
}
#results div:hover {background: lightblue;}
#results div span {
color: red;
font-weight: bold;
}
<form id="theForm">
Search for: <input name="search" class="searchInput"/>
</form>
<div id="results"></div>
Because in this section of code it relies on the form element to get the input element:
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
Other than that the form isn't needed. As such you could instead make it:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementsByClassName("searchInput")[0];
Or instead change your input element to have an id of "searchInput" instead of a class and do:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementById("searchInput");

Bind textbox value with dynamic div's

I am trying to append / (Bind) textbox innerhtml value to the dynamic div which has the pagination. When I am trying append with textbox with the div I am getting an error.
There are two elements in my initial page First One is for no of pages and other one is for enter some text. If I enter number 2 so two div will appear dynamically. Then I enter the greeting text second text box. Text should appear in the first div and for the second div if i click the button in the bottom second div should be empty. Using Pure javascript (Vanila).
I am trying to get value from the textbox. But I was not able to bind with the p tag which was available dynamically.
Kindly help me.
var gettext_Title = document.getElementById('title_Text')
var getresult = gettext_Title.value;
//alert(result);
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
hTitle = document.createElement('p');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
hTitle.setAttribute('id', ['Title' + (totalCount)]);
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the Jsfiddle Link
Thanks in advance
Kindly help me
Cheers,
If I understand correctly what you mean, try this:
main.js :
(function () {
var inputTitle,
inputElement,
current,
totalCount = 0;
document.addEventListener('DOMContentLoaded', function (e) {
inputTitle = document.getElementById('title_Text');
inputElement = document.getElementById("inputAdd_page");
inputElement.addEventListener('blur', onInputElementBlur);
inputTitle.addEventListener('blur', onInputTitleBlur);
});
function onInputTitleBlur(e) {
if (!!current) {
var title = current.querySelector('p');
title.innerText = inputTitle.value;
inputTitle.value = '';
}
}
function onInputElementBlur() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
var fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
var spancount = document.createElement('span');
var prevPage = document.createElement('div');
var navbutton = document.createElement('button');
var hTitle = document.createElement('p');
var preview_PageSize = document.getElementById('page');
var navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', 'pag_navg' + totalCount);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = 1 + totalCount;
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
current = pageEl;
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = 1 + totalCount;
hTitle.setAttribute('id', 'Title' + (totalCount));
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', 'page' + (totalCount));
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
current = document.querySelector('div[data-page="0"]');
inputElement.value = "";
document.body.appendChild(fragment);
}
}
}());
index.html :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myStyleSheet" href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<input type="text" class="form-control title_Textbox" id="title_Text" placeholder="Text">
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page"></div>
<div id="pageBtn" class="row pagination_btn"></div>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
style.css :
.div_navig {
background: lightGrey;
width: 24px;
height: 24px;
text-align: center;
margin-left: 5px;
color: black;
cursor: pointer;
}
.pagination_btn {
float: right;
margin: 0 20px 0 0;
padding-left: 5px;
}
.spanCount {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px 0 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
.title_boundry {
border: 1px dotted #000;
height: 40px;
}

Categories