I saw in a project a function that promoted random values from different objects in JavaScript and display content inside HTML tag,I want to make something like that but different. When I a button to take random value
to a single object and display it inside a div.
I create some object in JS and a action when click a button display object but I don't know how to put all content inside a div and to take random information.
function deosebitProject() {
var site_1 = {
name: "Site 1",
url: "https://www.google.ro/",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
}
var site_2 = {
name: "Site 2",
url: "https://www.google.ro/",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
}
document.write(
'<div class="container">',
'<div class="row">',
'<div class="col-md-6">',
'<h2>' + site_1.name + '</h2>',
'' + site_1.url + '',
'<p>' + site_1.description + '</p>',
'</div>',
'<div class="col-md-6">',
'<img src="' + site_1.site_image[0] + '"><br /> <img src =' + site_1.site_image[1] + '"><br /> <img src = "' + site_1.site_image[2] + '">',
'</div>',
'</div>',
'</div>'
);
document.write(
'<div class="container">',
'<div class="row">',
'<div class="col-md-6">',
'<h2>' + site_2.name + '</h2>',
'' + site_2.url + '',
'<p>' + site_2.description + '</p>',
'</div>',
'<div class="col-md-6">',
'<img src="' + site_2.site_image[0] + '"><br /> <img src =' + site_2.site_image[1] + '"><br /> <img src = "' + site_2.site_image[2] + '">',
'</div>',
'</div>',
'</div>'
);
}
<!doctype html>
<html>
<head>
<title>Javascript Challange 1</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="random.js"></script>
</head>
<body>
<div>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit, erat ac lobortis tristique, eros eros tristique enim, at imperdiet lectus orci fermentum ex. Suspendisse at nisl pretium, congue nunc sit amet, rutrum lectus. Integer eu luctus
metus. Duis placerat finibus urna eu euismod. Vestibulum mollis viverra lacinia. Curabitur odio elit, venenatis eget congue sit amet, sagittis bibendum risus. Donec pretium id justo nec elementum. Duis interdum non ligula at imperdiet. Nunc ultricies
ac arcu id aliquet. Ut vitae risus magna. Curabitur mollis placerat tortor, nec finibus mi elementum nec. Pellentesque vitae tortor elementum, porttitor magna sit amet, dapibus nisl. Nullam sed dolor id enim tempus porttitor. Curabitur eleifend
condimentum nisl, id placerat purus semper sed. Nulla facilisi. Donec vehicula tempor nulla a tempor. Nulla quis rhoncus elit. Aenean sagittis auctor turpis vel pharetra. Donec est nunc, molestie sit amet ullamcorper sed, facilisis nec sapien. Mauris
mauris quam, porta sed ante ut, egestas ultricies augue. Pellentesque ornare arcu ac vestibulum mattis. Sed nec malesuada turpis. Cras aliquam turpis nec justo tempus finibus. Morbi et luctus est.Curabitur eget malesuada neque. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Maecenas sed sagittis arcu. Maecenas quis orci quis lorem luctus feugiat placerat in tellus.
</p>
</div>
<div id="our-project">
<button onclick="deosebitProject()">View Project</button>
</div>
</body>
</html>
I don't really understand whout should be random, so I started with a random project display in the container.
Created an array of the project objects
Created a function that creates the HTML to be appended to the DOM container
Created a function that sets a random number from 0 to (project) array length, and appends the HTML to the DOM container
Decoupled the event from the DOM by using HTML.addEventListener(), and placed the random function there (on click event)
Now, if you press the button, a random project is selected from the array, and it is displayed in the container
const arr = [{
name: "Site 1",
url: "https://www.google.ro/",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
},
{
name: "Site 2",
url: "https://www.google.ro/",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
}
]
const projectHTML = (data) => {
let html = ''
html += '<div class="container">'
html += '<div class="row">'
html += '<div class="col-md-6">'
html += `<h2>${data.name}</h2>`
html += `${data.url}`
html += `<p>${data.description}'</p>`
html += '</div>'
html += '<div class="col-md-6">'
data.site_image.forEach((e, i, a) => {
html += `<img src="${data.site_image[i]}"`
i === a.length - 1 ? html += '' : html += '<br />'
})
html += '</div>'
html += '</div>'
html += '</div>'
return html
}
function deosebitProject(arr) {
const r = Math.floor(Math.random() * arr.length);
document.getElementById('content').innerHTML = projectHTML(arr[r])
}
const btn = document.getElementById('btn')
btn.addEventListener('click', function(e) {
deosebitProject(arr)
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div>
<p id="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit, erat ac lobortis tristique, eros eros tristique enim, at imperdiet lectus orci fermentum ex. Suspendisse at nisl pretium, congue nunc sit amet, rutrum lectus. Integer eu luctus
metus. Duis placerat finibus urna eu euismod. Vestibulum mollis viverra lacinia. Curabitur odio elit, venenatis eget congue sit amet, sagittis bibendum risus. Donec pretium id justo nec elementum. Duis interdum non ligula at imperdiet. Nunc ultricies
ac arcu id aliquet. Ut vitae risus magna. Curabitur mollis placerat tortor, nec finibus mi elementum nec. Pellentesque vitae tortor elementum, porttitor magna sit amet, dapibus nisl. Nullam sed dolor id enim tempus porttitor. Curabitur eleifend condimentum
nisl, id placerat purus semper sed. Nulla facilisi. Donec vehicula tempor nulla a tempor. Nulla quis rhoncus elit. Aenean sagittis auctor turpis vel pharetra. Donec est nunc, molestie sit amet ullamcorper sed, facilisis nec sapien. Mauris mauris quam,
porta sed ante ut, egestas ultricies augue. Pellentesque ornare arcu ac vestibulum mattis. Sed nec malesuada turpis. Cras aliquam turpis nec justo tempus finibus. Morbi et luctus est.Curabitur eget malesuada neque. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas sed sagittis arcu. Maecenas quis orci quis lorem luctus feugiat placerat in tellus.</p>
</div>
<div id="our-project">
<button id="btn">View Project</button>
</div>
EDIT
const projectHTML = (data) => {} is an arrow function (This is an arrow: =>). Most of the time arrow functions and traditional functions are interchangeable - most of the time!
The other difference is I used const instead of var. In this simple case this also makes no difference - const is a block-scoped variable, var is not.
data in my snippet is not a special object. I could have named it doggieDoo or anything (not reserved term, of course). this is a reserved keyword in JS.
So, basically they mean the same thing:
const projectHTML = (data) => {}
/*is the same as*/
var projectHTML = function(data) {}
I must emphasize though, that they do the same thing in this case!
You can read a lot more here:
Arrow functions vs traditional functions
https://medium.com/the-non-traditional-developer/arrow-functions-vs-traditional-functions-in-javascript-8ff1a48ede12
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?
Variable declarations:
var: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
const: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
let: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
this keyword:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
I think you'll get much more information by looking at the linked contents, than if I started explaining :)
Related
I want to get the height of the text inside a textarea. Here is the problem: the textarea has a fixed number of rows, causing the scrollHeight property to become useless in this case. See this example:
console.log(document.querySelector('textarea').scrollHeight);
<textarea rows="10">Hello, world!</textarea>
My idea was to remove the rows attribute with JavaScript, retrieve the scrollHeight, and reapply the attribute.
However, this causes jumps on the page in Safari, so it is not a solution.
Does anyone know of a property/function that return this value? Thanks in advance!
To be "more or less" bullet proof, solution has to consider the real computed size of your text.
const scrollOrNot = (el, nbline) => {
const divTest = document.querySelector('#test');
divTest.style.fontsize = el.style.fontsize;
divTest.style.lineHeight = el.style.lineHeight;
divTest.style.width = el.getBoundingClientRect().width + 'px';
divTest.innerHTML = 'W';
const h_one_line = divTest.getBoundingClientRect().height;
divTest.innerHTML = el.value;
if (Math.floor((divTest.getBoundingClientRect().height / h_one_line)) > nbline) {
console.log((divTest.getBoundingClientRect().height / h_one_line));
el.setAttribute('rows', 10);
}
}
scrollOrNot(document.querySelector('#textarea1'),10);
scrollOrNot(document.querySelector('#textarea2'),10);
#test {
position: absolute;
top: -3000px;
height: auto;
}
<textarea id="textarea1">Hello, world!</textarea>
<textarea id="textarea2">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Turpis massa tincidunt dui ut ornare lectus. Pellentesque dignissim enim sit amet venenatis urna. In fermentum posuere urna nec tincidunt. Venenatis urna cursus eget nunc scelerisque viverra mauris in. Non quam lacus suspendisse faucibus interdum posuere lorem ipsum. Nunc id cursus metus aliquam eleifend mi in nulla. Netus et malesuada fames ac turpis egestas integer eget. Sit amet dictum sit amet justo donec enim diam. Aliquam purus sit amet luctus venenatis lectus. Ligula ullamcorper malesuada proin libero nunc. Venenatis lectus magna fringilla urna porttitor rhoncus. Faucibus interdum posuere lorem ipsum dolor. Posuere ac ut consequat semper viverra nam libero justo laoreet. Ac turpis egestas sed tempus urna et pharetra pharetra massa. Vestibulum sed arcu non odio euismod lacinia. Arcu non odio euismod lacinia at quis risus sed. Lobortis mattis aliquam faucibus purus in massa tempor nec. Enim ut sem viverra aliquet eget sit amet tellus cras.
</textarea>
<div id="test"></div>
here you have a div at -3000px, absolute.
you put same width, fontsize and line height of your textarea.
You put a 'W' in it (biggest letter for latin character)
you take it's height
you put your text in
you take the new height
if division more than requested lines...
I created this very simple accordion. Everything works pretty well except when I am testing it on mobile. When there is a change in which content is visible there is this 'awkward jump' between the different elements. Also for some reason when I try to add the jQuery slideDown method it doesn't work so everything is jumping from section to section and it just feels awkward. Here is the code:
$(".container-out").click(function(){
$(".container-content").removeClass("active").eq($(this).index()).addClass("active");
});
.container-content {
display: none;
}
.active {
display: block;
}
h2 {
padding: 20px;
background: black;
color: white;
}
<div class="container-out">
<div class="container-link">
<h2>ONE</h2>
</div>
<div class="container-content active">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<div class="container-out">
<div class="container-link">
<h2>TWO</h2>
</div>
<div class="container-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<div class="container-out">
<div class="container-link">
<h2>THREE</h2>
</div>
<div class="container-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
Any suggestions are greatly appreciated!
Working example based on your code with slideDown.
$(".container-link").click(function(){
var $targetPanel = $(this).nextAll('.container-content');
if(!$targetPanel.hasClass('active')){
$('.container-content.active').removeClass('active').slideUp();
$targetPanel.addClass('active').slideDown();
}
});
.container-content {
display: none;
}
.active {
}
h2 {
padding: 20px;
background: black;
color: white;
}
<div class="container-out">
<div class="container-link">
<h2>ONE</h2>
</div>
<div class="container-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<div class="container-out">
<div class="container-link">
<h2>TWO</h2>
</div>
<div class="container-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<div class="container-out">
<div class="container-link">
<h2>THREE</h2>
</div>
<div class="container-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra. Fringilla ut morbi tincidunt augue interdum velit euismod in pellentesque. Lobortis scelerisque fermentum dui faucibus in ornare quam. Eget lorem dolor sed viverra ipsum nunc. At erat pellentesque adipiscing commodo elit. Viverra nam libero justo laoreet. Leo duis ut diam quam nulla porttitor. Euismod nisi porta lorem mollis aliquam ut. Aliquam etiam erat velit scelerisque in. Nibh cras pulvinar mattis nunc sed blandit libero. Massa tincidunt dui ut ornare lectus sit amet est placerat. Consectetur libero id faucibus nisl tincidunt eget nullam non nisi. Porta nibh venenatis cras sed felis eget.
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
I am trying to hover over a button and trigger a page scroll slowly. Not scroll to ID but slowly scroll the page on hover and to stop scrolling when Not hovered.
I’m not sure to understand your request, maybe you need something like that :
let elem = document.querySelector('#myElem');
let interval;
let maxScrollHeight = elem.scrollHeight - elem.clientHeight;
elem.addEventListener('mouseenter', function() {
interval = setInterval(function() {
elem.scroll(0, elem.scrollTop += 10);
// This part of code is for replay
if (elem.scrollTop >= maxScrollHeight) {
elem.scroll(0, 1);
}
}, 100);
});
elem.addEventListener('mouseleave', function() {
clearInterval(interval);
});
p {
max-height: 100px;
max-width: 100px;
overflow: scroll;
}
<p id="myElem">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
A simple solution could be the use of a timer function with setTimeout() Method, using window.scroll function with behavior:'smooth' in the object argument.
var scrollStep=10,
scrollTimer=null
function scrollSlowly(yDisplacement){
if(scrollTimer!=null)clearTimeout(scrollTimer);
scrollTimer = setTimeout(function(){
window.scroll({
top:window.scrollY+yDisplacement,
left:0,
behavior: 'smooth'
})
scrollSlowly(yDisplacement)
}, 100);
}
document.getElementById('up').addEventListener('mouseenter',function(evt){
scrollSlowly(-scrollStep)
})
document.getElementById('up').addEventListener('mouseleave',function(evt){
if(scrollTimer!=null)clearTimeout(scrollTimer);
})
document.getElementById('down').addEventListener('mouseenter',function(evt){
scrollSlowly(scrollStep)
})
document.getElementById('down').addEventListener('mouseleave',function(evt){
if(scrollTimer!=null)clearTimeout(scrollTimer);
})
.toolbar{
position:fixed;
top:0.5em;
left:0.5em;
}
body{
padding:2em;
}
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a est sit amet nisi tempus feugiat at quis felis. Aenean sit amet pretium lectus, non faucibus tortor. Suspendisse potenti. Aenean posuere lorem in ultricies malesuada. Cras vulputate tincidunt augue, in vulputate lacus iaculis id. Vestibulum et neque sed quam vestibulum laoreet in eget nunc. Suspendisse potenti.
</p>
<p>
Suspendisse molestie pretium suscipit. Morbi vitae dictum neque. Nullam a purus eu tortor iaculis eleifend nec eget augue. Maecenas bibendum neque vitae felis tincidunt laoreet. Nunc faucibus ligula sed tellus luctus porttitor sed a leo. Vivamus feugiat bibendum neque in consectetur. Integer dignissim tristique augue sed fermentum. Curabitur id feugiat tortor.
</p>
<p>
Sed ligula massa, sollicitudin ac feugiat non, elementum in augue. Pellentesque vel nibh at erat lobortis volutpat. Nunc ex leo, pretium ut egestas sit amet, scelerisque eleifend dolor. Proin dictum, odio non semper viverra, leo leo cursus nunc, ac varius neque diam vitae metus. Quisque id mi convallis, lobortis massa eget, posuere dolor. Aliquam magna dolor, malesuada id ullamcorper vel, rutrum non orci. Fusce rutrum placerat risus, eget molestie massa malesuada et. Duis rhoncus vestibulum turpis. Nullam gravida id est at posuere. Sed vel cursus tortor, quis rutrum leo. Nulla id nibh quis tellus fringilla mattis quis vel lorem. Sed accumsan magna nunc, ut tempus leo venenatis in. Mauris semper tortor a viverra tempus.
Sed nec orci quis risus pellentesque ultricies sed in mi. Nam et mauris eros. Quisque in rhoncus justo, ac mattis nulla. Sed eget nibh nibh. Aenean nisl sapien, congue a purus posuere, pretium egestas sapien. Pellentesque tempus orci ut placerat luctus. Sed tincidunt, urna vel ornare fermentum, ligula mauris pulvinar tortor, ac convallis libero nibh convallis tortor.
</p>
<p>
Donec eget odio elit. Praesent viverra nisi magna, quis rhoncus enim pellentesque sit amet. Pellentesque sodales blandit mauris ac laoreet. Morbi pharetra pellentesque ex eu sodales. Morbi id tempus lacus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In nec tincidunt ex. Duis commodo nibh vel tincidunt aliquam. Etiam vel risus sed sem placerat auctor. Nulla porta sapien lorem, et molestie massa interdum ac.
</p>
<div class='toolbar'>
<button id='up'>Up</button><button id='down'>down</button>
</div>
</body>
i have a unique case here. So i have 2 divs, one on the left and one on right. How can i make it so that if the height of left div exceeds the height of the div on right, the function should make the heights equal and hide any text for the left div. So if i calculate the offsetheight on load and for one on right is 443 px and one on left is 583 px, it should make both heights equal and height the rest 140px of data of left one.
I created a pen
var text = document.getElementById('overflow_text')
function mounted() {
var toggleBtn = document.getElementById('toggle_text')
var offsetDiv = document.getElementById('offset_height')
var offsetDivHeight = offsetDiv.offsetHeight + 'px'
var textHeight = text.offsetHeight + 'px'
console.log(textHeight)
console.log(offsetDivHeight)
if (textHeight > offsetHeight) {
text.style.maxHeight = offsetDivHeight
text.style.overflow = 'hidden'
text.style.textOverflow = 'ellipsis'
text.style.whiteSpace = 'nowrap'
}
}
#toggle_text {
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<body onLoad='mounted()'>
<div class="container">
<div class="row">
<div class="col-md-6">
<p id='overflow_text' class="readMore">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum.
Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.
Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec</p>
<span onClick="myFunction()" id="toggle_text">Read More</span>
</div>
<div class="col-md-6">
<p id="offset_height">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum.
Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est,Donec vitae dui
eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae
scelerisque enim ligula venenatis dolor. Maecenas nisl estDonec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est </p>
</div>
</div>
</div>
</body>
So if you check the console, you will see what the heights of both divs are onLoad. Not sure how i can set the CSS through Javascript. Thank you in advance.
If any one has any other ideas on how to achieve this, i am open to suggestions.
The solution is a bit tricky, since you cannot simply use textOverflow: ellipsis css property if your text has multiple lines.
First we set height of the left text container to the height of the right which is smaller. Then we have to shrink the number of words displayed inside the left container. We remove words from the end of the container until container's scrollHeight is smaller or equal to the container's height.
In this way we know that the container has only as much words as it's able to display with restriction that it's no taller than the right container.
The drawback is that we remove overflowing words from the element so you're no longer able to get original content from this container.
function mounted() {
var leftContainer = document.getElementById('overflow_text')
var rightContainer = document.getElementById('offset_height')
var rightOffsetHeight = rightContainer.offsetHeight;
var leftOffsetHeight = leftContainer.offsetHeight;
if (leftOffsetHeight > rightOffsetHeight) {
leftContainer.style.height = rightOffsetHeight + "px"
var wordArray = leftContainer.innerHTML.split(' ');
while(leftContainer.scrollHeight > leftContainer.offsetHeight) {
wordArray.pop();
leftContainer.innerHTML = wordArray.join(' ') + '...';
}
}
}
Your if statement needs to use the variable name, offsetDivHeight.
if (textHeight > offsetHeight)
offsetHeight is never defined. Do you mean offsetDivHeight?
text.style.whiteSpace = 'nowrap'
If you do this, all of the text in the div will be confined to one line.
Demo with these changes made.
I know there are many solutions to stopping an element from scrolling after a certain point using JQuery, but I'd like to do it with vanilla Javascript.
Basically, this is an element that fixes once you scroll down to it and I want it to stop being fixed at the bottom of the page so that it doesn't go under the footer, if that makes sense.
Here is my current Javascript:
var fixmeTop = $('#childWidth').offset().top; //get initial position
$(window).scroll(function() {
var currentScroll = $(window).scrollTop(); // get current position
if (currentScroll >= fixmeTop - 100) { // fix once scroll to or past element
var elementAdd = document.getElementById("childWidth");
elementAdd.classList.add("afix");
} else {
var elementRemove = document.getElementById("childWidth");
elementRemove.classList.remove("afix");
}
});
The CSS which fixes the element:
.afix {
position:fixed;
z-index;9999;
top:100px;
}
I tried getting #childWidth's distance from the bottom of the page and then adding a CSS class with position:absolute; once scrolled within a certain distance from the bottom of the page but the element just disappeared once I scrolled down to near the bottom.
I believe you are looking for position: sticky. This would be a pure CSS solution; no JS necessary:
.HolyGrail {
display: flex;
min-height: 100vh;
flex-direction: column;
}
.HolyGrail-body {
display: flex;
flex: 1;
background-color: pink;
}
.HolyGrail-content {
flex: 1;
background-color: aqua;
}
.HolyGrail-nav, .HolyGrail-ads {
/* 12em is the width of the columns */
flex: 0 0 12em;
background-color: red;
}
.HolyGrail-nav {
/* put the nav on the left */
order: -1;
background-color: yellow;
}
header, footer { height: 100px; }
header { background-color: blue; }
footer { background-color: green; }
.nav-box-wrapper {
position: sticky;
top: 50px;
}
.nav-box {
background-color: magenta;
position: relative;
top: 100px;
}
<!-- https://philipwalton.github.io/solved-by-flexbox/demos/holy-grail/ -->
<div class="HolyGrail">
<header>…</header>
<div class="HolyGrail-body">
<main class="HolyGrail-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Enim diam vulputate ut pharetra sit amet aliquam id. Nisi scelerisque eu ultrices vitae auctor. In dictum non </p>
<p>consectetur a erat nam at lectus. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Diam phasellus vestibulum lorem sed. Tincidunt eget nullam non nisi est sit. Donec massa sapien faucibus et molestie ac feugiat sed
<p>Est velit egestas dui id ornare arcu odio ut sem. Facilisi nullam vehicula ipsum a arcu cursus vitae congue. Ut consequat semper viverra nam libero. Congue nisi vitae suscipit tellus mauris a diam. Interdum velit laoreet id donec ultrices
<p>tincidunt arcu. Morbi tincidunt ornare massa eget egestas. Feugiat in fermentum posuere urna nec tincidunt. Etiam dignissim diam quis enim. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Lacus luctus accumsan tortor
<p>posuere ac ut consequat semper viverra. Lobortis mattis aliquam faucibus purus in massa.</p>
</main>
<nav class="HolyGrail-nav">
<div class="nav-box-wrapper">
<div class="nav-box">
<ul>
<li>link 1</li>
<li>link 2</li>
<li>link 3</li>
<li>link 4</li>
<li>link 5</li>
<li>link 6</li>
<li>link 7</li>
<li>link 8</li>
<li>link 9</li>
</ul>
</div>
</div>
</nav>
<aside class="HolyGrail-ads">…</aside>
</div>
<footer>…</footer>
</div>
Please excuse all the ugly lorem ipsum -- if you run this full screen you should be able to see it in action.
This was sort of quick slipshod together-- there might be better approaches, and you'd want to do plenty of browser testing. But the sticky position property would probably allow what you are describing without the need for any code outside your HTML and CSS.