I am trying to calculate the width and difference between the widths of a div and the text in a page where the same div class appears multiple times.
The HTML:
<div class="post_content">
<div class="container">
<div class="title-holder">
<h2>Crossword Book</h2>
</div>
</div>
<div class="container">
<div class="title-holder">
<h2>Crossword Bookstore Ltd. – Elgin Road</h2>
</div>
</div>
</div>
The CSS:
div.container{
width: 130px;
}
div.title-holder {
width: 130px;
height:20px;
text-align:center;
background: silver;
overflow:hidden;
position: relative;
}
div.title-holder a {
position: relative;
white-space:nowrap;
left: 0px;
}
div.image{
background: brown;
width: 100%;
height: 100px;
}
The following script outputs the result of the first div correctly and then repeats the same result. It is not going to the next div and giving the next result.
$("div.title-holder").each(function(){
var m = $(this).width();
var n = $("div.title-holder h2 a.widget-title").width();
var o = m - n;
alert ("title: " + m + " text: " + n + " diff: " + o);
});
The output is
First Alert: title: 130 text: 108 diff: 22
Second Alert: title: 130 text: 108 diff: 22
What I am looking to achieve is
First Alert: title: 130 text: 108 diff: 22
Second Alert: title: 130 text: 258 diff: -128
The value of:
var n = $("div.title-holder h2 a.widget-title").width();
Will always be the same (the first result of that selector query). You need to do:
var n = $(this).find("a.widget-title").width();
or more specific:
var n = $("div.title-holder").children("h2").children("a.widget-title").width();
Use like this:
var n = $(this).find("h2 a.widget-title").width();
jsBin demo
$("div.title-holder").each(function(){
var m = $(this).width();
var n = $("h2 a.widget-title", this).width();
var o = m - n;
alert("title: " + m + " text: " + n + " diff: " + o);
});
Related
I have made some code but problem is that I need to use jQuery append again and again for every line. I am not sure that how can I make it short so that as I enter values in textarea, it automatically add or delete lines as many as required (because this code will be difficult if I have 100 or 200 lines to append).
$(document).ready(function() {
$('.position').bind("change keyup input", function() {
var pos = $('.position').val().split(',');
var hght = $('.height').val().split(',');
var lbl = $('.label').val().split(',');
$('.peak').remove();
$('.matchi').append("<div class='peak' style='left:" + pos[0] + "%;height:" + hght[0] + "%'>" + lbl[0] + "</div>").append("<div class='peak' style='left:" + pos[1] + "%;height:" + hght[1] + "%'>" + lbl[1] + "</div>").append("<div class='peak' style='left:" + pos[2] + "%;height:" + hght[2] + "%'>" + lbl[2] + "</div>").append("<div class='peak' style='left:" + pos[3] + "%;height:" + hght[3] + "%'>" + lbl[3] + "</div>")
});
});
.peak {
background: red;
height: 100%;
width: 0.5%;
position: absolute;
bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
you can map() the compiled html based on the .position value
$(document).ready(function() {
$('.position, .height, .label').on("input", function() {
var pos = $('.position').val().split(',');
var hght = $('.height').val().split(',');
var lbl = $('.label').val().split(',');
$('.peak').remove();
let html = pos.map((p, i) => `<div class='peak' style='left:${pos[i]}%;height:${hght[i]}%'>${lbl[i]?lbl[i]:''}</div>`);
$('.matchi').html(html)
});
});
.peak {
background: red;
height: 100%;
width: 0.5%;
position: absolute;
bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Here is my javascript:
$('#vendorid').change(function(){
var vendno = $(this).val();
var data_String;
var numpo = parseInt($('#numvendpo').val());
data_String = 'vendorid='+vendno;
$.post('ft-vendno.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val($('#vendponum').val() + data +'-'+ numpo+1);
});
});
My output is:
As seen in the bottom textbox the last number "-31" should be "-4" (3+1). Whereas it is currently adding it as a string. I can't seem to figure out the problem though.
The top textbox is #numvendpo and the bottom is #vendponum forgive me for my confusing variable names.
When you do:
some_string + numpo + 1
As the first value is a string, you are concatenating values from right to left, so you would first concatenate numpo (converting it to string) to some_string, and then 1, also as a string.
You can fix that making sure the operations are done in the right order, so one option might be to add parenthesis around numpo + 1:
$('#vendponum').val($('#vendponum').val() + data + '-' + (numpo + 1));
You can also do the sum before:
var numpo = parseInt($('#numvendpo').val()) + 1;
Or use template strings:
$('#vendponum').val(`${ $('#vendponum').val() }${ data }-${ numpo + 1 }`);
Here you can see what works and what does not:
const $vendorid = $('#vendorid');
const $numvendpo = $('#numvendpo');
const $outputParenthesis = $('#outputParenthesis');
const $outputBefore = $('#outputBefore');
const $outputTemplate = $('#outputTemplate');
const $outputWrong = $('#outputWrong');
$('#vendorid, #numvendpo').on('input', () => {
const vendno = $vendorid.val();
const numpo = parseInt($numvendpo.val());
if (isNaN(numpo)) {
return;
}
const numpoPlusOne = numpo + 1;
$outputParenthesis.text(vendno + '-' + (numpo + 1));
$outputBefore.text(vendno + '-' + numpoPlusOne);
$outputTemplate.text(`${ vendno }-${ numpo + 1 }`);
$outputWrong.text(vendno + '-' + numpo + 1);
});
body,
input {
font-family: monospace;
}
input {
border: 3px solid black;
padding: 8px;
width: 200px;
}
p {
margin: 8px 0;
}
.label {
display: inline-block;
width: 222px;
text-align: right;
margin-right: 8px;
}
.wrong {
color: red;
}
<input placeholder="Vendor ID" id="vendorid" type="text" />
<input placeholder="Num Vendor PO" id="numvendpo" type="text" />
<p><span class="label">WITH PARENTHESIS: </span><span id="outputParenthesis"></span></p>
<p><span class="label">SUM BEFORE: </span><span id="outputBefore"></span></p>
<p><span class="label">TEMPLATE LITERAL: </span><span id="outputTemplate"></span></p>
<p class="wrong"><span class="label">WRONG: </span><span id="outputWrong"></span></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have created a bus seat layout dynamically ....
and i have selected seats are pushed to array...
and how to print the array values in html DOM.....
below is my html code
<div>
<h2> Choose seats by clicking the corresponding seat in the layout below:</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
below is my css
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
verticle-align:middle;
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
}
below is my js
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
// Add already reserved seats
localStorage.setItem('SeatNum', JSON.stringify(reservedSeat));
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
var selectedSeat = JSON.parse(localStorage.getItem('SeatNum'));
if($(this).hasClass(settings.selectingSeatCss)){
// Add seat in local storage
selectedSeat.push(parseInt($(this).find('a').text()));
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
else{
// Remove seat from local storage
selectedSeat.splice(selectedSeat.indexOf(parseInt($(this).find('a').text())), 1);
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
}
// Logging
console.log('Reserved and selecting seats : ' + JSON.parse(localStorage.getItem('SeatNum')));
});
$('#btnShow').click(function myFunction() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
how to print the array values in html DOM....
i put an alert..
i tried code but that does't work..
i created bus seat layout dynamically i am putting an alert to show the selected seats and all seats but i want to print the selected seat in html Dom....
Take a div in the end of your html
and then put that line where you set the alert
$('#showSit').text(JSON.parse(localStorage.getItem('SeatNum')));
I am trying to get the height of an element with it's sub-pixel value.
Take this example:
var small = document.getElementById('small');
var big = document.getElementById('big');
var result1 = document.getElementById('result1');
result1.innerHTML = 'Small height: ' + small.clientHeight + '; width: ' + small.clientWidth + '; ratio: ' + (small.clientWidth / small.clientHeight) + ';';
result2.innerHTML = 'Big height: ' + big.clientHeight + '; width: ' + big.clientWidth + '; ratio: ' + (big.clientWidth / big.clientHeight) + ';';
body {
margin: 0;
}
img {
float: left;
}
#small {
width: 3px;
}
div {
float: left;
font-size: 2rem;
}
<div id="result1"></div>
<div id="result2"></div>
<img src="https://i.imgur.com/580DosTm.jpg" id="small">
<img src="https://i.imgur.com/580DosTm.jpg" id="big">
Basically you can see the same image in a big size and in a very small size. In the small one the width is set to 3px. The real height is 4.51562px (can be seen in Chrome developer tools). However, JavaScript rounds the number to 5px.
What I am actually behind is the ratio. As you can see the difference ends up being big:
Small image ratio: 0.6 (3/5)
Big image ratio: 0.6625 (212/320)
The big image ratio is the real one because the image is not resized. Is there some way to get the real values of the height, or at least something closer than a per pixel unit round?
The closest value I can get is reading the computed CSS properties with getComputedStyle and getting the values from there:
parseFloat(getComputedStyle(small));
It gives me in Chrome:
Small height: 4.51562
Small ratio: 0.6643605972158861 (3/4.51562)
var small = document.getElementById('small');
var big = document.getElementById('big');
var result1 = document.getElementById('result1');
var smallStyles = getComputedStyle(small);
var smallHeight = parseFloat(smallStyles.height);
var smallWidth = parseFloat(smallStyles.width);
result1.innerHTML = 'Small height: ' + smallHeight + '; width: ' + smallWidth + '; ratio: ' + (smallWidth / smallHeight) + ';';
result2.innerHTML = 'Big height: ' + big.clientHeight + '; width: ' + big.clientWidth + '; ratio: ' + (big.clientWidth / big.clientHeight) + ';';
body {
margin: 0;
}
img {
float: left;
}
#small {
width: 3px;
}
div {
float: left;
font-size: 2rem;
}
<div id="result1"></div>
<div id="result2"></div>
<img src="https://i.imgur.com/580DosTm.jpg" id="small">
<img src="https://i.imgur.com/580DosTm.jpg" id="big">
without using funtion, when i use for (var prop in obj) which will show me all value in the object. However when i tried to put in function, it just show up me with the first value in the object which not show me the second element ( studentID ). :(
var target = document.getElementById("outputArea");
var outstring = " ";
var myObj = {
name: "Nguyen Viet Tien",
StudentID: "26813157",
};
function tellAll(obj) {
var dis = " ";
for(var prop in obj) {
dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";
return dis;
}
}
outstring += tellAll(myObj);
target.innerHTML = outstring;
<html lang="en">
<head>
<meta charset="utf-8">
<title>Eng1003 Workshop Code Week 04</title>
<style>
#outputArea {
padding: .25em;
border: solid black 2px;
margin: 3em;
height: 20em;
width: 20em;
overflow-y: scroll;
font-family: arial "sans serif";
font-size: 1em;
color: rgb(50, 50, 250);
background-color: rgb(225,225,225) ;
}
</style>
</head>
<body>
<div id="outputArea"></div>
</body>
</html>
return statement in the wrong place
function tellAll(obj) {
var dis = " ";
for(var prop in obj) {
dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";
}
return dis;
}