Create a JavaScript class "ModifyParagraph", here constructor accepts paragraph element. inside the constructor, create 4 buttons (which change the paragraph, Bold, color, size, position) using document.createElement and add click event handler on each. Click handler on bold button will turn on/off the boldness.
My code:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Question-2</title>
<meta charset="UTF-8">
<script src="q2.js"></script>
<link rel="stylesheet" href="q2.css" />
</head>
<body>
<div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div>
</body>
</ul>
</html>
JavaScript
class ModifyParagraph{
constructor(myDIV){
this.myDIV = myDIV;
function myFunction(){
var btn = document.createElement("BUTTON");
var bold = document.getElementById(myDIV);
btn.addEventListener('click', function(){
if (bold.style['font-weight']) {
bold.style.removeProperty('font-weight');
} else {
bold.style['font-weight'] = "800";
}
}
}
}
}
In my code, I have a problem in creating a button inside the constructor and adding click handlers on each button. Please let me know how to proceed
Apart from your syntax mistakes(I'll cover them later in the answer), your main issue is that you missed to append the created button to the DOM.
Here's a working demo:
class ModifyParagraph {
constructor(div) {
this.myDIV = div;
}
toggleBoldStyle() {
// create the button.
var btn = document.createElement('button');
// give it some text/value.
btn.textContent = 'toggle Bold styling';
// add click event listener to the button.
btn.addEventListener('click', function() {
// if the font-weight is 800 make it 'normal' else if it's other than 800 make it 800'
// add the 'this' keyword in the addEventListener method references the button, to get the member myDIV we'll just call it without preceding it by 'this'(myDIV in place of this.myDIV).
myDIV.style.fontWeight = (myDIV.style.fontWeight === '800') ? 'normal':'800';
});
// append the button to the DOM
this.myDIV.appendChild(btn);
}
}
// testing...
var p = new ModifyParagraph(document.getElementById('myDIV'));
p.toggleBoldStyle();
<div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div>
Apart from missing to append the button to the DOM, you had some mistakes:
Class methods doesn't require the 'function' keyword, you have to just write the method name.
You missed a closing parenthesis of the addEventListener method.
Why you're trying to get the element that you just saaved in the muyDIV member. Better, you have two choices: send the element itself to the constructor or send it's ID and in the assignment to the myDIV member you fetch the element by the getElementById method. In my demo I sent the element itself to the constructor. But, you can make things more complicated to allow sending the ID or the element itself possible, innthe constructor you have to check the type of the incoming argument.
Finally, here's the link of the MDN documentation of the ECMAScript 5 classes.
Hope I pushed you further.
My code,
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Question-2</title>
<meta charset="UTF-8">
<script src="q2.js"></script>
</head>
<body>
<div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div>
</body>
</ul>
</html>
JavaScript
class ModifyParagraph {
constructor(div) {
this.myDIV = div;
}
toggleBoldStyle() {
// create the button.
var btn = document.createElement('button');
// give it some text/value.
btn.textContent = 'toggle Bold styling';
// add click event listener to the button.
btn.addEventListener('click', function() {
// if the font-weight is 800 make it 'normal' else if it's other than 800 make it 800'
// add the 'this' keyword in the addEventListener method references the button, to get the member myDIV we'll just call it without preceding it by 'this'(myDIV in place of this.myDIV).
myDIV.style.fontWeight = (myDIV.style.fontWeight === '800') ? 'normal':'800';
});
// append the button to the DOM
this.myDIV.appendChild(btn);
}
}
// testing...
var p = new ModifyParagraph(document.getElementById('myDIV'));
p.toggleBoldStyle();
Related
I'm trying to use window.find() in JavaScript to find and select text across elements. Overall it works as expected, except across <p> elements (or line breaks?).
Here's my simplified HTML:
findText("first with style"); // true
findText("second"); // true
findText("third"); // true
findText("second\nthird"); // false
findText("second\n\nthird"); // false
findText("second\rthird"); // false
findText("second\r\nthird"); // false
findText("second<br>third"); // false
findText("second</p><p>third"); // false
findText("second
third"); // false
function findText(needle) {
console.log(window.find(needle));
}
.as-console-wrapper{ max-height:75px !important; }
<p>first<b> with style</b></p>
<p>second</p>
<p>third</p>
Here's a JS fiddle.
What am I missing?
I don't think any browser allows doing multiline search with their native search feature, so it's normal the DOM API doesn't either, since it's supposed to more or less mirror that feature.
If all you want to do is to check if the given text is present in the current visible text, you can get the document's innerText which will return only the visible text (here "visible" means the ones that are rendered, not necessarily the ones that are in screen).
const text = document.documentElement.innerText;
const toFind = "orci.\n\nPhasellus"; // end of first paragraph + start of second.
console.log(text.includes(toFind));
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed malesuada, massa nec elementum imperdiet, enim arcu fringilla purus, ac bibendum massa augue nec odio. Donec vel hendrerit ligula. Maecenas ante dolor, faucibus tristique commodo non, sollicitudin
at augue. In lobortis quis est a mattis. Aenean blandit lorem at porta ultrices. Nullam sit amet mauris a justo congue iaculis. Duis urna velit, luctus vel tempus quis, consequat id ex. Etiam accumsan urna ac imperdiet gravida. Etiam gravida rhoncus
quam sit amet placerat. In tincidunt lorem non lacus semper hendrerit. Phasellus nec ultrices orci.
</p>
<p>
Phasellus sit amet porttitor leo. Phasellus ut eleifend nulla. Morbi luctus odio quis risus aliquam fermentum. Aenean ultrices tortor leo, eu fermentum tortor tincidunt in. Maecenas sodales nisl erat, nec porta tortor mollis non. Donec vulputate non quam
imperdiet ornare. Integer ex mauris, hendrerit in est sed, sagittis lacinia nulla. Curabitur efficitur dui et neque condimentum, eu lacinia nisi rutrum.
</p>
<p>
Ut vel lorem id justo sodales venenatis. Vestibulum nec mattis risus. Ut a imperdiet lacus, eget molestie dolor. Sed nisl diam, facilisis a nunc non, faucibus suscipit diam. Quisque aliquet, eros sed sodales cursus, ex metus vulputate ante, sagittis dapibus
leo diam sed ligula. Fusce felis nulla, euismod in facilisis vel, viverra sed eros. Praesent ut diam quis nunc ultrices dignissim et vitae ligula. Donec quam orci, consequat eget leo sit amet, fringilla tempus leo. Nullam felis enim, sodales non lectus
ut, pretium tincidunt felis. Sed eget odio sit amet nunc consequat vulputate. Vivamus nisl nisl, condimentum vitae malesuada non, tempus ac metus. Nulla placerat arcu eu risus feugiat, efficitur semper diam fringilla. Curabitur et blandit felis. Curabitur
vel eleifend mi.
</p>
<p>
Maecenas tincidunt mi vestibulum nisi aliquet, at rhoncus mi tristique. Nullam sagittis sed dolor ut aliquet. Sed neque nunc, pulvinar vel ornare id, convallis ut nulla. Integer rhoncus velit non pulvinar commodo. Praesent finibus libero ante, eget venenatis
augue dignissim id. Nam id odio id ante maximus blandit vel nec purus. Sed eleifend leo ut commodo maximus. Nam pretium a mauris a scelerisque.
</p>
<p>
Duis laoreet lorem a nibh dapibus sodales. Curabitur ac orci scelerisque lorem maximus blandit nec ut leo. Nulla feugiat maximus congue. Proin velit leo, suscipit et mollis eu, tempor non eros. Morbi nec mi non lectus auctor fermentum vitae at lectus.
Sed ut massa sapien. Vivamus eu ipsum quis ante mollis volutpat at ac ipsum. Vivamus ut est sem. Quisque eget nulla posuere sapien rutrum ullamcorper. Donec porta nisl quis quam dignissim elementum sit amet ut turpis. Suspendisse ullamcorper non sapien
vitae faucibus. Praesent mollis bibendum pretium. Donec auctor lectus nec urna tincidunt egestas vitae vel quam. Sed a neque eleifend, elementum metus quis, sagittis diam. Pellentesque id purus sed nulla euismod tincidunt.
</p>
</div>
If you also need to select the text, you might be able to do so with the Selection API and walking over every node to find where the match was, but that will be quite tedious to build that, so I leave it as an exercise for now.
Maximum you can do is to query for elements and select in between:
findText("first with style"); // true
findText("second"); // true
findText("third"); // true
findMultiple("body p:nth-child(2)","body p:nth-child(4)"); // true
function findText(needle){
console.log(window.find(needle));
}
function findMultiple(start,end){
var range = document.createRange();
var root_node = document.body;
range.setStart(root_node.querySelector(start).firstChild, 0);
range.setEnd(root_node.querySelector(end).firstChild, root_node.querySelector(end).innerText.length);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
<p>first<b> with style</b></p>
<p>second</p>
<p>middle</p>
<p>third</p>
You could also querySelect all elements and check if contains your text, store that element then run the function. But that can be slower, depends.
Please refer this solution - JavaScript window.find doesn't work absolutely
Below solution will give us the boolean value based on the matches of string irrespective of the lines.
I hope you're looking for the below one.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p>first<b> with style</b></p>
<p>second</p>
<p>third</p>
<p id="demo"></p>
<script>
let name = window.name;
document.getElementById("demo").innerHTML = "Result of matching: "+ containsStr$("second third");
function containsStr$(str) {
return $('body:contains("'+str+'")').length > 0;
}
</script>
</body>
I am attempting to implement readmore.js into my code but I am continuously running into readmore.js is not a function error. I've read over the documentation multiple times and I am unable to figure out what I am doing wrong. When implemented correctly should include a "READ MORE" button to expand the text in its entirety.
I've included the HTML script tag that is presented in the github
I've made sure I included a jquery cdn before the readmore.js
I've included a class name of article
I've attempted to wrap the .readmore in a function such as :
$(function () { $('.article').readmore({speed: 75, lessLink: 'Read less'});});
Here is a snippet of code that I am working with:
const data = [{ paragraph: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id aliquam nibh. Aenean a porttitor ipsum. Vestibulum ut sagittis dui, nec pharetra eros. Vivamus tempus fringilla dictum. Maecenas facilisis auctor magna, a accumsan nunc molestie dictum. In tempus rhoncus condimentum. Aenean interdum leo et velit pellentesque dapibus. Vivamus nunc orci, commodo sit amet dui a, lobortis finibus arcu. Maecenas metus mauris, tincidunt sit amet ex id, gravida commodo nunc. Donec consequat tristique lacinia. Pellentesque commodo eu tortor sit amet rutrum. Vivamus mollis eros ipsum, in vestibulum lorem tempor sit amet. Morbi egestas orci sem, posuere rutrum augue malesuada eget. Mauris ultricies egestas luctus. Praesent at dignissim nunc. Aliquam erat volutpat."},{
paragraph: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam porttitor tincidunt fringilla. In ullamcorper vitae sapien eget ornare. Nulla quis lacus condimentum lacus tincidunt consectetur ut in ante. Suspendisse a eleifend est. Pellentesque eu ornare magna. Vestibulum ac mi sit amet arcu tristique volutpat in id nisl. Aenean interdum et odio gravida hendrerit. Pellentesque at diam lacus. Mauris elementum ultricies imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus ligula, molestie at laoreet id, convallis et felis. Nullam molestie, augue vel interdum semper, dui massa feugiat risus, non sodales est massa non arcu. Vivamus ut sodales metus."
}
]
let htmlOutput = ""
for (let i = 0; i < data.length; i++) {
htmlOutput += "<div>" + data[i].paragraph + "</div>"
}
$("#report").html(htmlOutput)
$('.article').readmore({
speed: 75,
lessLink: 'Read less'
});
<div id="report" class="article">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/node_modules/readmore-js/readmore.min.js"></script>
My expected outcome is to be able to include the .readmore function and have a "read more" that will expand the text once clicked.
You will have to download the readmore.min.js file from the repo. The file is located here.
https://github.com/jedfoster/Readmore.js/blob/master/readmore.min.js
Then you can include it in your project by putting it in the same directory as your index.html file and add a script tag like this
<script src="readmore.min.js"></script>
hi this might have been solved but ill add my 2c.
from your code it seem that you are adding the text inside a nested div instead of the parent div with the article class.
try adding "id='report' class= 'article' " inside the for loop div and check if the plugin works
I'm in the process of learning React and am trying to achieve something that I was able to do quite easily before with jQuery. I want to do this purely in React though and have found a solution that gets me part of the way there but not entirely...
Basically I have a div that houses text. By default I have a class that sets a height to that element, I then have another class that removes the height restriction allowing for all the content to be visible.
In jQuery it would have been a simple one or two lines to remove the restricted height class and add on my non-restricted one.
Here is my React code thus far:
import React, { Component } from 'react'
import arrow from "./img/down-arrow.png";
class UserGen extends Component {
constructor(props) {
super(props);
this.state = {
active: false
}
}
handleClick() {
this.setState({
active: !this.state.active
})
}
render() {
return (
<div className="user-generated col-md-8 offset-md-2 col-sm-12">
<div onClick={this.handleClick.bind(this)} className= {this.state.active ? " user-generated-inner ug-expanded" : " user-generated-inner ug-collapsed"}>
<h4>User Generated Summary</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tempus auctor magna in fermentum. Sed et arcu vitae sem elementum consequat. Sed rhoncus vestibulum risus, eu tempor diam faucibus a. In efficitur accumsan scelerisque. Ut convallis nulla nec eros consectetur, ut consectetur tellus accumsan. Aenean quam tortor, consequat quis ligula quis, posuere laoreet risus. Nam id cursus ligula, et sagittis libero. Nam id dui vel diam eleifend accumsan. Donec aliquet, enim vitae dapibus maximus, turpis ante cursus enim, iaculis mollis nibh quam lacinia magna. Curabitur metus lorem, posuere blandit tortor eget, molestie viverra purus. Mauris in justo eget velit suscipit convallis. Aliquam placerat mi nec erat venenatis tincidunt vel vitae ligula. Nulla mattis justo id lacus posuere, in fringilla ex commodo. Ut at sem ligula.</p>
<p>Duis eu diam ut urna egestas interdum. Integer sapien ligula, ultricies ac lobortis id, accumsan quis nisl. Donec pharetra condimentum mattis. Aliquam pretium lacinia ultricies. Maecenas vehicula nisi velit, dignissim consectetur nulla molestie ut. Suspendisse dictum porta semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras condimentum rhoncus volutpat. Fusce placerat, metus id finibus maximus, augue tellus hendrerit lacus, quis maximus magna erat et nisl. Aenean non leo metus. Suspendisse potenti. Maecenas sit amet lobortis nunc, ut vehicula tortor. Duis maximus est vel tortor vulputate dignissim. Integer ac laoreet risus, et ultricies mi.</p>
<p>Mauris est lorem, lobortis id accumsan faucibus, aliquet in ante. In porttitor nisl sit amet risus feugiat maximus. Mauris commodo dignissim fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sodales, nunc et dictum placerat, mi lacus placerat enim, nec faucibus sapien enim vel felis. Fusce ultricies condimentum mauris, eget accumsan risus dictum id. Mauris tincidunt, ipsum at suscipit faucibus, tortor ligula volutpat ante, a cursus sapien lacus non sem. Maecenas consectetur, felis et scelerisque laoreet, turpis turpis gravida turpis, eget vestibulum magna tellus et ex. Mauris dignissim lorem non dui ornare ullamcorper. Mauris interdum bibendum augue. Proin egestas laoreet sapien nec sodales.</p>
</div>
<div className="expand"><p>Read More<span className="expand-arrow"><img src={arrow} alt="arrow for the read more" /></span></p></div>
</div>
);
}
}
export default UserGen
This works... but I've only been able to figure out how to get this running if it's the div housing the content that I'm clicking on.
Ideally I want to be able to fire the same onClick function from my "expand" class.
Any help is greatly appreciated, as is any constructive feedback on how this code looks.
Generally your code looks fine and you're almost there. You just need to add the same handleClick method, which I renamed to toggleActive, to the div.expanded as its onClick prop. This will also trigger the same action.
import React, { Component } from "react";
import arrow from "./img/down-arrow.png";
class UserGen extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
};
}
toggleActive = () => {
this.setState({
active: !this.state.active,
});
};
render() {
const { active } = this.state;
const containerClass = `user-generated-inner ug-${
active ? "expanded" : "collapsed"
}`;
return (
<div className="user-generated col-md-8 offset-md-2 col-sm-12">
<div onClick={this.toggleActive} className={containerClass}>
<h4>User Generated Summary</h4>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum
tempus auctor magna in fermentum. Sed et arcu vitae sem elementum
consequat. Sed rhoncus vestibulum risus, eu tempor diam faucibus a.
In efficitur accumsan scelerisque. Ut convallis nulla nec eros
consectetur, ut consectetur tellus accumsan. Aenean quam tortor,
consequat quis ligula quis, posuere laoreet risus. Nam id cursus
ligula, et sagittis libero. Nam id dui vel diam eleifend accumsan.
Donec aliquet, enim vitae dapibus maximus, turpis ante cursus enim,
iaculis mollis nibh quam lacinia magna. Curabitur metus lorem,
posuere blandit tortor eget, molestie viverra purus. Mauris in justo
eget velit suscipit convallis. Aliquam placerat mi nec erat
venenatis tincidunt vel vitae ligula. Nulla mattis justo id lacus
posuere, in fringilla ex commodo. Ut at sem ligula.
</p>
<p>
Duis eu diam ut urna egestas interdum. Integer sapien ligula,
ultricies ac lobortis id, accumsan quis nisl. Donec pharetra
condimentum mattis. Aliquam pretium lacinia ultricies. Maecenas
vehicula nisi velit, dignissim consectetur nulla molestie ut.
Suspendisse dictum porta semper. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Cras condimentum rhoncus volutpat.
Fusce placerat, metus id finibus maximus, augue tellus hendrerit
lacus, quis maximus magna erat et nisl. Aenean non leo metus.
Suspendisse potenti. Maecenas sit amet lobortis nunc, ut vehicula
tortor. Duis maximus est vel tortor vulputate dignissim. Integer ac
laoreet risus, et ultricies mi.
</p>
<p>
Mauris est lorem, lobortis id accumsan faucibus, aliquet in ante. In
porttitor nisl sit amet risus feugiat maximus. Mauris commodo
dignissim fringilla. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Fusce sodales, nunc et dictum placerat, mi lacus
placerat enim, nec faucibus sapien enim vel felis. Fusce ultricies
condimentum mauris, eget accumsan risus dictum id. Mauris tincidunt,
ipsum at suscipit faucibus, tortor ligula volutpat ante, a cursus
sapien lacus non sem. Maecenas consectetur, felis et scelerisque
laoreet, turpis turpis gravida turpis, eget vestibulum magna tellus
et ex. Mauris dignissim lorem non dui ornare ullamcorper. Mauris
interdum bibendum augue. Proin egestas laoreet sapien nec sodales.
</p>
</div>
<div className="expand" onClick={this.toggleActive}>
<p>
Read More
<span className="expand-arrow">
<img src={arrow} alt="arrow for the read more" />
</span>
</p>
</div>
</div>
);
}
}
export default UserGen;
If you wish to only expand and not collapse on the div.expanded you need to create a new function that only sets active in your state to true.
expand = () => {
this.setState({ active: true });
}
Hope this helps!
EDIT: Trying to answer the question in the comment section.
(Needed to be here, as the text would have been too long.)
I'm not sure if I understood the question. However, I'm going to try to answer: Your component UserGen has an internal state which in this case consists only of the boolean active. Now in your render method you're doing specific things based on the current value of boolean active of the state. The render method doesn't care where the state change came from, it simply takes the state and does what you told it to do.
To demonstrate this on another level, you could even add your components setState method to the window object and change the state from your dev tools, without clicking on any element on the page. The component would still simply render whatever you told it to depending on the current state.
// (...)
constructor(props) {
super(props);
this.state = {
active: false,
};
// Do this only for demonstration purposes, do not ship this
window.__userGenSetState = this.setState;
}
Now in your dev tools simply call __userGenSetState({ active: true }) or __userGenSetState({ active: false }) and you'll see that the render method doesn't care where the state change came from.
I think you can achieve what you want to do with using React Ref's.Here is a official documentation for how to implemet them.
https://tr.reactjs.org/docs/forwarding-refs.html
I am creating a website for a client and they have given me some very strict limitations. The html must be coded in one document (index.html), with the javascript and css each in their own separate document. They also want me to use Angular or Node only if necessary (it has not been necessary so far).
Since they are requiring multiple “pages” on the website, I am using Javascript to hide or unhide different divs corresponding to each page. I also have the separate divs internally referenced. Therefore, when the maps “page” is open the URL displays as https:\\site.com\#maps . When the page gets reloaded, it ignores the #maps and simply returns to the main “page”.
I have tried using window.location to get the url when the page is loaded, then pass that to my function; however, that has not worked. I also briefly tried messing with cookies to save the page location, but wasnt able to get very far with it.
How can I get the function to load the page I want based on the url?
function openPage(evt, PageName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the link that opened the tab
document.getElementById(PageName).style.display = "block";
evt.currentTarget.className += " active";
//set the page cookie
var expiry = new Date();
expiry.setTime(expiry.getTime()+600000);
expires = "; expires=" + expiry.toUTCString();
document.cookie = "Page=" + PageName + expires + " ; path=/";
}
Well, each div element has to have the id attribute, this attribute identifies the page/div and will be set as value for the window.location.hash.
Than handle all click events which trigger the page change, for instance all a elements with href attribute set to these ids.
Then create function which will show/hide the desired page, and call this method when the whole html page is loaded.
Here is an example using jQuery (if you want there is no need to use jQuery, you can do it with vanilla javascript as well):
$(function() {
// Method wich show/hide pages
function showpage(target) {
// Target is the id of the page div
var $target = $(target);
// If there is not any page with that id do nothing
if(!$target.length) {
return;
}
// Hide all pages
$(".page").css("display", "none");
// Show the target page
$target.css("display", "block");
// Update the window has
window.location.hash = target;
}
// Handle clicks which show pages
$(document).on("click", "a[href^='#']", function (e) {
e.preventDefault();
showpage($(this).attr("href"));
});
showpage(window.location.hash);
});
.page {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
page1
</li>
<li>
page2
</li>
<li>
page3
</li>
<li>
page4
</li>
</ul>
<div id="page1" class="page">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus interdum velit pretium porttitor aliquam. Proin a lectus nec ligula laoreet tempor. In ornare volutpat velit, non semper mauris accumsan nec. Aliquam nibh nisi, pellentesque eu mauris eu, fringilla faucibus leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pretium, tortor eget scelerisque luctus, enim quam elementum diam, ac varius elit tortor eu tortor. Morbi molestie massa nec aliquam fringilla.
</div>
<div id="page2" class="page">
Maecenas sagittis convallis turpis, sed fermentum magna porttitor eget. Aenean et lectus eu velit interdum aliquet. Duis faucibus sollicitudin iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent suscipit pulvinar felis, at fermentum dolor ultrices non. Maecenas malesuada urna lorem, mollis lobortis nisi semper et. Quisque ac tellus interdum, hendrerit nisl eu, feugiat ante. Nullam tincidunt ex non metus venenatis suscipit. Duis rutrum convallis erat, quis ultrices nunc efficitur sed. Donec lacinia tellus eu neque tempus, eu bibendum odio sollicitudin. Nullam convallis ligula vitae sapien tristique, eget ullamcorper risus pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec tincidunt, sapien vel eleifend laoreet, tortor dolor ultrices est, consequat suscipit neque metus a velit. Maecenas cursus nec arcu et varius. Nulla ex lorem, mollis eu risus quis, molestie dapibus nisl. Maecenas vel imperdiet mauris, ut pretium odio.
</div>
<div id="page3" class="page">
Donec mi mi, placerat tincidunt justo sit amet, facilisis congue sapien. Nunc lacinia lobortis turpis ac rhoncus. Donec tempus elit vitae pharetra congue. Nam at dolor at metus hendrerit pharetra nec et velit. Morbi iaculis ipsum non finibus hendrerit. Nunc eget ex non augue feugiat venenatis a sit amet nisl. Vestibulum elementum ipsum non enim pulvinar malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et purus vitae libero lobortis gravida et eu lectus. Aenean dignissim molestie ante a iaculis.
</div>
<div id="page4" class="page">
Pellentesque iaculis diam a condimentum aliquam. Integer vestibulum interdum ligula, quis tempus felis aliquam at. Ut vel tincidunt purus, quis convallis ipsum. Pellentesque massa velit, varius gravida purus nec, consectetur suscipit nibh. Vivamus vel dui sit amet magna condimentum sodales ac a urna. Sed viverra, dolor sit amet facilisis commodo, tortor massa efficitur neque, sit amet sollicitudin lectus augue sed est. Nulla dapibus facilisis magna, vestibulum maximus dui gravida convallis. Sed sit amet tellus non velit tincidunt mollis vitae vitae purus. Donec sed molestie lacus. Morbi condimentum sapien nec odio scelerisque bibendum.
</div>
Use the onload property on your body tag:
<body onload="pageLoaded(window.location.hash)">
https://www.w3schools.com/jsref/event_onload.asp
I want to create a preloader of my full page.
<body>
<div id="preload-content">Please wait</div>
<div id="body-container" style="background-image:url(very-big-image-file.jpg);">
// page contents goes here
</div>
</body>
now i have a huge image in my #body-container.
i use jQuery and when i use .ready() function page appears but images are still loading.
$("body").ready(function() {
$("#preload-content").delay(500).fadeOut(400, function() {
$("#body-container").fadeIn(200);
$("body").css("background-color","#fff").css("color","#000");
});
});
$(document).ready() is not working either.
i want to show #body-container after all images, plugins, scripts, css files loaded succesfully!
so... how can i do this.
You can try.
$("body").ready(function() {
// Create a image object
var bgImage = new Image();
// bind loading event
$(bgImage).bind("onload",function(){
// Set the background css
$("#body-container").css('background-image','url(very-big-image-file.jpg)');
// Fade your preloader content
$("#preload-content").delay(500).fadeOut(400, function() {
$("#body-container").fadeIn(200);
$("body").css("background-color","#fff").css("color","#000");
});
});
//Start loading your image
bgImage.src = "very-big-image-file.jpg";
});
Apologize for some typo error. But the concept is like that.
When you call $("anything").ready() it all goes to the same place (and event handler when the DOM is ready, not necessarily all resources), the selector actually doesn't matter.
What you want here though is window.onload, which fires when images have loaded as well, like this:
$(window).load(function() {
$("#preload-content").delay(500).fadeOut(400, function() {
$("#body-container").fadeIn(200);
$("body").css("background-color","#fff").css("color","#000");
});
});
Make sure this is outside of any document.ready handlers, as there's a chance the onload event already executed then.
Try this one:
<html>
<head>
<!-- Include the heartcode canvasloader js file -->
<script src="http://heartcode-canvasloader.googlecode.com/files/heartcode-canvasloader-min-0.9.1.js"></script>
<style type="text/css">
body, html {
margin:0;
padding:0;
overflow:hidden;
background-color:#353535;
}
.wrapper {
position:absolute;
top:50%;
left:50%;
}
#contenedor {
background-color: #fff;
}
</style>
</head>
<body onLoad="document.getElementById('precarga').style.visibility='hidden';document.getElementById('contenedor').style.visibility='visible';" >
<div id="precarga" style="visibility: visible">
<!-- Create a div which will be the canvasloader wrapper -->
<div id="canvasloader-container" class="wrapper"></div>
<!-- This script creates a new CanvasLoader instance and places it in the wrapper div -->
<script type="text/javascript">
var cl = new CanvasLoader('canvasloader-container');
cl.setColor('#9e9e9e'); // default is '#000000'
cl.setShape('spiral'); // default is 'oval'
cl.setDiameter(200); // default is 40
cl.setDensity(160); // default is 40
cl.setRange(1); // default is 1.3
cl.setSpeed(1); // default is 2
cl.setFPS(60); // default is 24
cl.show(); // Hidden by default
// This bit is only for positioning - not necessary
var loaderObj = document.getElementById("canvasLoader");
loaderObj.style.position = "absolute";
loaderObj.style["top"] = cl.getDiameter() * -0.5 + "px";
loaderObj.style["left"] = cl.getDiameter() * -0.5 + "px";
</script>
</div>
<div id="contenedor" style="visibility: hidden">
<!-- Modify this with your content [start] -->
<p align="justify">
Lorem ipsum dolor sit amet, sit rhoncus tellus tristique ipsum, etiam enim commodo purus ligula, dui praesent vivamus fusce vel, justo vitae nesciunt suspendisse. Pretium elit maecenas mollis pellentesque, leo in vestibulum vitae habitasse dolor lacus, elit pharetra nec cras suspendisse, lectus eget nulla elit. Ut sapien velit quis accumsan nibh varius. Nunc maecenas, eu sapien porttitor convallis, nullam cras. Dolores mauris cum at velit, mauris posuere nunc euismod. Vel leo volutpat scelerisque aliquam mi.</p>
<p align="justify">
Aenean sed per nec in facilisis ullamcorper, mattis cras neque mauris fusce. Non odio gravida et, aliquet laoreet ac consequat risus, ut ridiculus sit massa est. A tristique adipiscing nulla, vel interdum magna. Luctus tincidunt curabitur erat ac, nisl praesent odio, in ullamcorper sem, proin tortor, dignissim feugiat orci non quam vitae mi. Id amet, vitae magna nunc velit vel, cras wisi tincidunt magnam at donec venenatis. Rutrum quis turpis eget. Nec quis donec sed non ultrices gravida, suscipit varius vivamus, velit libero quis imperdiet molestie.</p>
<p align="justify">
Pellentesque ornare eu lacus non, pede tempus velit duis, gravida nam phasellus sem, amet accumsan tincidunt wisi. Et libero et neque, aliquam pretium rerum neque, feugiat malesuada est sed autem a platea, lectus ultrices. Vitae tristique aliquet, tincidunt wisi velit odio sodales nunc nunc. Sed tincidunt turpis a nullam magna, sagittis vestibulum pellentesque integer montes neque, nunc odio neque diam lorem integer, sociis eu. Maecenas ut lectus senectus auctor dictum, ligula volutpat nulla pulvinar nam pellentesque pellentesque, vitae morbi magna dui in risus, aliquam vel mi odio purus duis suspendisse, justo mattis morbi integer. Pretium nec a, duis nunc mi, in vel. Lacus dui, eros nulla justo sollicitudin. Turpis et et pharetra non.</p>
<p align="justify">
Nunc maecenas turpis, vel in sed eget arcu, elit vitae. Curabitur et odio in ornare metus est. Massa porttitor consectetuer. Vitae bibendum, consectetuer duis diam quam in, est etiam aliquam enim molestie scelerisque. Vestibulum sed eros ac vitae lectus. A leo, quod volutpat id et lacus vitae vitae. Aenean tellus vivamus parturient metus, pellentesque ut lorem ut orci nisl. Ut et id luctus eros, feugiat in malesuada tellus quisque, iaculis tristique, nonummy massa voluptas vel. Elit a erat pulvinar sem sagittis, ligula eget est amet, a tristique ut ac wisi, gravida donec et eget nec. Amet nec, ut non penatibus eget, ornare purus sollicitudin a tincidunt vitae rutrum, commodo non faucibus, aut pretium risus lorem nulla egestas auctor.</p>
<p align="justify">
</p>
<img src="http://v11.nonxt8.c.bigcache.googleapis.com/static.panoramio.com/photos/original/21785753.jpg?redirect_counter=1"/>
<!-- Modify this with your content [end] -->
</div>
</body>
</html>