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
Related
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
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();
I'm trying to toggle an image on Click. It's partially working but also partially not :'(
Demo: http://jsfiddle.net/Tqwdh/4/.
When I click the large image, the smaller image changes (from 50x50 to 151x151) - hurrah!
But when I click the 'Read more' text, the small image remains the same image. The small, nested image needs to change when I click the 'Read more' text.
Can anyone show me how I can resolve this?
I've attached my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});
$(function(){
$("article").click(function(){
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50'
)
)
});
});
and my HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Praesent sem lectus, ullamcorper eget ullamcorper a, congue vel nisl. Nullam volutpat leo vel dui venenatis dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus ac scelerisque lorem. Ut blandit magna eu turpis posuere gravida. Fusce egestas risus in libero ullamcorper sagittis. Vestibulum molestie metus vitae quam dignissim consequat. Vivamus id tellus id lorem consectetur iaculis sit amet interdum ante. Quisque lacinia tellus id mi tincidunt fermentum dignissim velit laoreet. Quisque scelerisque nunc iaculis nisi varius ultrices.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/50x50" class="small" style="position:absolute;margin-left: 240px;margin-top: 127px;" />
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article>
Many thanks for any pointers.
So, if I have understood you correctly, all you've got to do is,
Change this
$("article").click(function() {
//your code here
});
to,
$("article, .adjust").click(function() {
//your code here
});
Check the fiddle here
EDIT:
Changed a couple of things to match what you needed,
1) Change this,
$(this).parents('article').find('.adjust').click();
to,
$(this).parents('article').find('.adjust').trigger('click');
as the latter is a proper way to trigger an event.
2) Change in the image swap function,
$("article, .adjust").click(function() {
/*Save references in variables*/
var imgToSwap = $(this).parents("article").find("img.small");
var img_small = 'http://placehold.it/50x50';
var img_large = 'http://placehold.it/151x151';
imgToSwap.attr('src', (imgToSwap.attr('src') == img_small ? img_large : img_small));
});
Using $(this) will help you get the image in the right context.
Check the fiddle test here
It looks like you have a few problems here. I don't see that you've applied the adjust class to any element in your HTML. I also see that CSS is applied directly in JavaScript. (Why not use a .css file?)
This part of the code looks very nice:
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
This is good use of the ternary operator.
My I suggest that you use this code as the click handler on a.adjust, assuming that the link that expands the image is supposed to be decorated with the adjust class?
var changeImage = function() {
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
});
$('a.adjust').click(changeImage);
$('article').click(changeImage);
I hope this helps. If the question were written more precisely, it might be helpful.
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>