I am using the following code to dynamically add items to a page. I have each component as an object then I call each individual one with a For-in loop.
My question is, how can I convert my data to JSON, and then import it into my JS file to use?
const pageObjects = {
objectComponent1 : {
provideTitle: "Title",
provideId: "title",
provideDesc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Bibendum ut tristique et egestas quis ipsum suspendisse ultrices. Id aliquet risus feugiat in. Eget velit aliquet sagittis id consectetur purus. Non consectetur a erat nam at lectus urna duis. Convallis aenean et tortor at risus viverra adipiscing at. ",
provideHtml: `<p class="test">This is a pragraph element.</p>`,
},
objectComponent2: {
provideTitle: "Title",
provideId: "title",
provideDesc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Bibendum ut tristique et egestas quis ipsum suspendisse ultrices. Id aliquet risus feugiat in. Eget velit aliquet sagittis id consectetur purus. Non consectetur a erat nam at lectus urna duis. Convallis aenean et tortor at risus viverra adipiscing at.",
provideHtml: `<p class="test">This is a pragraph element.</p>`,
},
};
const docsContent = document.querySelector(".docs-content");
for (const singleObject in pageObjects) {
// add title
let objectTitle = document.createElement("h2");
objectTitle.setAttribute("id", pageObjects[singleObject].provideId);
objectTitle.innerHTML = pageObjects[singleObject].provideTitle;
docsContent.append(objectTitle);
// add description
let objectDesc = document.createElement("p");
objectDesc.innerHTML = pageObjects[singleObject].provideDesc;
docsContent.append(objectDesc);
// add example
let objectExample = document.createElement("div");
objectExample.classList.add("docs-example");
objectExample.innerHTML = pageObjects[singleObject].provideHtml;
docsContent.append(objectExample);
// add provide code
let objectCode = document.createElement("div");
objectCode.classList.add("docs-code");
docsContent.append(objectCode);
let pre = document.createElement("pre");
objectCode.append(pre);
let code = document.createElement("code");
code.innerHTML = pageObjects[singleObject].provideHtml;
pre.append(code);
};
Related
I have a string like:
const content = 'Lorem ipsum dolor {image} sit amet, consectetur adipiscing elit {image}. Sed quis varius erat. Pellentesque in {image} magna feugiat mi imperdiet suscipit. Pellentesque eget lobortis justo. {image} Sed id pretium purus.'
And an array like:
const images = ['https://images.website.com/61ea8cc09233173e0ff27b1b.jpg','https://images.website.com/61ea8cc39233173e0ff27b24.jpg','https://images.website.com/61ea8cc59233173e0ff27b2d.jpg','https://images.website.com/61ea8cc89233173e0ff27b36.jpg']
And I would like to replace first {image} with images[0], second {image} with images[1], , third {image} with images[2]...
This script can be used for this purpose
let s="{image} b {image} c {image}"
let images=['image1','image2','image3']
images.forEach(img=>{s=s.replace('{image}',img)})
console.log(s)
It really depends on what you are trying to do. The simplest approach would be the following. For a more robust approach though, for instance, if you aren't just replacing '{image}' or if the array possibly doesn't have the same number of parameters as the replacements in the strings, etc, you will probably want to use RegEx.
var content = 'Lorem ipsum dolor {image} sit amet, consectetur adipiscing elit {image}. Sed quis varius erat. Pellentesque in {image} magna feugiat mi imperdiet suscipit. Pellentesque eget lobortis justo. {image} Sed id pretium purus.';
const images = ['https://images.website.com/61ea8cc09233173e0ff27b1b.jpg','https://images.website.com/61ea8cc39233173e0ff27b24.jpg','https://images.website.com/61ea8cc59233173e0ff27b2d.jpg','https://images.website.com/61ea8cc89233173e0ff27b36.jpg'];
for (var i = 0, l = images.length; i < l; i++) {
content = content.replace('{image}', images[i]);
}
console.log(content);
You can do as follow:
const content = 'Lorem ipsum dolor {image} sit amet, consectetur adipiscing elit {image}. Sed quis varius erat. Pellentesque in {image} magna feugiat mi imperdiet suscipit. Pellentesque eget lobortis justo. {image} Sed id pretium purus.'
const images = ['https://images.website.com/61ea8cc09233173e0ff27b1b.jpg','https://images.website.com/61ea8cc39233173e0ff27b24.jpg','https://images.website.com/61ea8cc59233173e0ff27b2d.jpg','https://images.website.com/61ea8cc89233173e0ff27b36.jpg']
let result = content
images.forEach((img) => {
result = result.replace('{image}', img)
})
console.log(result);
Use a template literal:
const content = `Lorem ipsum dolor ${image[0]} sit amet, consectetur adipiscing elit ${image[1]}. Sed quis varius erat. Pellentesque in ${image[2]} magna feugiat mi imperdiet suscipit. Pellentesque eget lobortis justo. ${image[3]} Sed id pretium purus.`
Note the use of backticks around the string instead of quotes.
function replaceWithImages(str, images) {
const images_ = [...images].reverse();
return str.replace(/{image}/g, () => images_.pop() || '');
}
The benefit of doing it this way is that you only need to create one new copy of str
I'm trying to access my local database using map method but always encountered this error.
I want to access my array of objects and display it using cards components.
Searched everywhere about my syntax but i can't seem to find any, is there an error of my code?
Here is my code:
import React, { Component } from 'react'
import { Container } from "react-bootstrap";
import products from '../database/db.json'
import {
Card,
Button
} from 'react-bootstrap'
export default class Home extends Component {
render() {
return(
products.map((products)=> {
return(
<Card style={{ width: '18rem', marginTop: '15px', marginRight: '15px' }} key={products.id}>
<div>
<Card.Img variant="top" src={products.images[0]} />
</div>
<Card.Body>
<Card.Title>{products.name}</Card.Title>
<Card.Text><strong>IDR {products.price.toLocaleString()},00</strong></Card.Text>
<div>
<Button variant="outline-light">
<i className="far fa-bookmark"></i>
</Button>
{/* <Button variant="outline-light" as={Link} to={`/detail?${item.id}`}>
<i className="fas fa-cart-plus"></i> Buy Now
</Button> */}
</div>
</Card.Body>
</Card>
)
})
)
and here is my database :
{
"products": [
{
"id": 1,
"name": "Nike Air Brown",
"img": "https://images.unsplash.com/photo-1549298916-b41d501d3772?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1000&q=80",
"price": 1987000,
"stock": 8,
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus faucibus. In fermentum et sollicitudin ac orci phasellus egestas tellus. Eget sit amet tellus cras. "
},
{
"id": 2,
"name": "Nike Air Jordan",
"img": "https://images.unsplash.com/photo-1597248881519-db089d3744a5?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80",
"price": 2543000,
"stock": 9,
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus faucibus. In fermentum et sollicitudin ac orci phasellus egestas tellus. Eget sit amet tellus cras. "
},
{
"id": 3,
"name": "Nike Revolt",
"img": "https://images.unsplash.com/photo-1542291026-7eec264c27ff?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80",
"price": 1765000,
"stock": 6,
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus faucibus. In fermentum et sollicitudin ac orci phasellus egestas tellus. Eget sit amet tellus cras. "
},
{
"id": 4,
"name": "Nike Green",
"img": "https://images.unsplash.com/photo-1596568359553-a56de6970068?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1028&q=80",
"price": 2143000,
"stock": 7,
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus faucibus. In fermentum et sollicitudin ac orci phasellus egestas tellus. Eget sit amet tellus cras. "
}
],
"users": [],
"transactions": []
}
import products from '../database/db.json' refers to the entire JSON object, so you need to access the products key, i.e. products.products.map((products)=> { .....
It may make more sense to import it as a different name, like data.
import data from '../database/db.json';
...
data.products.map((product) => { ..... }
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 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 :)
So I got the following code to create a simple fixed red box:
var red_box = document.createElement('div');
red_box.id = 'caixa_apresentacao_texto';
red_box.style.width = "40%";
red_box.style.overflow = "hidden";
red_box.style.backgroundColor = "white";
red_box.style.color = "black";
red_box.style.border = "5px double red";
/* Centralizing */
red_box.style.position = "fixed";
red_box.style.left = "50%";
red_box.style.marginLeft = "-20%"; //Por que a largura é 40%...
red_box.style.transition = "max-height 1s";
red_box.style.display = "none";
red_box.style.zIndex = "99999999999999";
red_box.style.marginTop = "50px";
red_box.style.maxHeight = "0px";
document.documentElement.insertBefore(red_box,document.body);
So, the idea is that, when I pass some text to this box, it enlarges slowly in order to display it. I get this behaviour with the following code:
var timerHeight;
function expandBox(text){
clearInterval(timerHeight);
/* if the box is empty...*/
if(document.querySelector("#red_box").style.maxHeight == "0px"){
document.querySelector("#red_box").style.display = "inline-block";
red_box.innerHTML = text;
/* Call a function that enlarge the maxHeight property , theorically with the transition letting it more beautiful */
var someText = "text";
timerHeight= setTimeout(enlargeBoxHeight(someText),1);
}
}
function enlargeBoxHeight(anyText){
document.querySelector("#red_box").style.maxHeight ="50px";
}
expandBox("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sollicitudin euismod metus, at blandit neque maximus ac. Integer fermentum nulla at nibh suscipit, a placerat est pretium. Morbi varius ornare enim, ac pulvinar elit aliquet in. Nullam non diam in nibh consectetur fringilla id nec enim. Mauris lacinia a augue ac consectetur. Etiam tempor et elit a dictum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum pulvinar pharetra. Aliquam erat volutpat. Aliquam non diam eget turpis tincidunt venenatis at in est. Duis laoreet nibh ultrices erat faucibus hendrerit.")
You can see the fiddle here.
So, I know that 50px is not a good height, but what matters here is that the transition is not working. You may have noticed that the var someText is useless here; but it does have the purpose to express my doubt. I've tried to take it off of the enlargeBoxHeight call. So the last part of the code now is:
...
timerHeight= setTimeout(enlargeBoxHeight,1);
}
}
function enlargeBoxHeight(){
document.querySelector("#red_box").style.maxHeight ="50px";
}
expandBox("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sollicitudin euismod metus, at blandit neque maximus ac. Integer fermentum nulla at nibh suscipit, a placerat est pretium. Morbi varius ornare enim, ac pulvinar elit aliquet in. Nullam non diam in nibh consectetur fringilla id nec enim. Mauris lacinia a augue ac consectetur. Etiam tempor et elit a dictum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum pulvinar pharetra. Aliquam erat volutpat. Aliquam non diam eget turpis tincidunt venenatis at in est. Duis laoreet nibh ultrices erat faucibus hendrerit.")
And the surprise: the transition works now. Why? What I am missing here?
When you do:
setTimeout(enlargeBoxHeight,1);
Without the parentheses (), you pass the function enlargeBoxHeight to the timeout, without calling it yet. The timeout will call it after 1ms. Which produced expected behavior + transition.
When you do:
timerHeight= setTimeout(enlargeBoxHeight(someText),1);
You pass the result of the function enlargeBoxHeight to the timeout. () part forces javascript to immediately call the function, and process everything before the timeout. So the transition does not work. After the 1ms, javascript handles the result (with is undefined or irrelevant).
If you want to pass a parameter to a timeout, do:
timerHeight= setTimeout(enlargeBoxHeight.bind(someText),1);
Which should work as expected.