I have a hover element in which when user hover over it will get text from a hidden element and when it hovers out it will reassign in its previous value.
My html is sort of like this.
<div id="product-name">Hover Here</div>
<br>
<div id="result-content">Lorem ipsum dolor sit amet.</div>
<div class="hidden">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla pellentesque mi leo, ut cursus tellus tempor nec. Sed facilisis augue neque, a ornare urna ornare in. Etiam consequat, dui sit amet pretium bibendum, ante ipsum ullamcorper libero, vel tempus erat urna sed purus. Quisque id ultricies elit, non posuere nunc. Etiam pulvinar magna tortor, at aliquet turpis interdum et. Duis imperdiet enim ante, sit amet pretium enim aliquet venenatis. Donec ac nibh nibh. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi aliquam est adipiscing volutpat pulvinar. Curabitur leo augue, iaculis id lacus sed, dictum vestibulum nulla. Etiam sit amet tempus felis, ac aliquet erat. Nunc ullamcorper consequat mattis. In molestie, tortor ac venenatis dapibus, eros neque vulputate nulla, in tristique ante diam non turpis. Maecenas mattis in risus eu ornare. Cras a rutrum nulla. Proin sagittis justo vehicula augue porttitor vulputate.
</div>
and javascript is this:
var object = document.getElementById("product-name");
object.onmouseover=function(){
document.getElementById("result-content").innerHTML = document.getElementsByClassName("hidden")[0].innerHTML;
};
object.onmouseout=function(){
document.getElementById("result-content")[0].innerHTML = document.getElementById("result-content").innerHTML;
};
jsfiddle.net
But my mouseout event failed me here. Can anyone help me out here how can i resolve this. I can't use jQuery in this dom only javascript, but I wouldn't mind if anybody show me a better approach to resolve javascript mouseout/mouseover paradigm.
Fiddle Demo
You need to store initial contents of the block.
var object = document.getElementById("product-name");
var currentHtml = document.getElementById("result-content").innerHTML;
object.onmouseover=function(){
document.getElementById("result-content").innerHTML = document.getElementsByClassName("hidden")[0].innerHTML;
this.onmouseout=function(){
document.getElementById("result-content").innerHTML = currentHtml;
}
};
document.getElementById("result-content")[0].innerHTML = document.getElementById("result-content").innerHTML; will take you nowhere. You have to preserve the value somewhere.
If you fancy a bit different approach then try this.
document.querySelector("#product-name").addEventListener("mouseover", function(){
var txt = document.querySelector("#result-content").innerHTML;
document.querySelector("#result-content").innerHTML = document.querySelector(".hidden").innerHTML;
this.addEventListener("mouseout", function(){
document.querySelector("#result-content").innerHTML = txt;
});
});
jsfiddle Demo
document.querySelector is supported in most browser.
http://caniuse.com/queryselector
I think, in this case must save somewhere previous state, like:
var object = document.getElementById("product-name"),
previous_state = document.getElementById("result-content").innerHTML;
Might not be the best approach, but without major changes in code should look like this:
jsfiddle
try this one for mouse out
object.onmouseout=function(){
document.getElementById("result-content").innerHTML ='Lorem ipsum dolor sit amet.';
};
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 trying to implement a function that yields highlighted and summarized preview of the given text. Please see the following code snippet.
<div>
Search:
<input value='vestibulum' disabled/>
</div>
<div style='margin-top: 20px'>Output I want:</div>
<div style='border: 1px solid #000; padding: 10px'>
...diam lectus <mark>vestibulum</mark> risus, eu <mark>vestibulum</mark> turpis quam in lorem. Vivamus posuere nibh leo, sit amet pharetra velit convallis sed. Sed porta convallis justo ac auctor. <mark>Vestibulum</mark> ante ipsum primis in faucibus orci luctus...
</div>
<div style='margin-top: 20px'>Original Text:</div>
<div style='border: 1px solid #000; padding: 10px'>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean at lacus tempus, pharetra dui vel, egestas massa. Integer metus enim, varius sed quam sed, convallis volutpat lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam efficitur, tortor quis sagittis sollicitudin, diam lectus vestibulum risus, eu vestibulum turpis quam in lorem. Vivamus posuere nibh leo, sit amet pharetra velit convallis sed. Sed porta convallis justo ac auctor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla et luctus leo, eu dignissim nunc. Phasellus vel fringilla sapien. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean et dui ut ipsum pretium ullamcorper. Aenean hendrerit dolor et lorem auctor ullamcorper.
</p>
<p>
Donec aliquet, purus ut tempor efficitur, velit eros luctus turpis, in pretium elit augue vel eros. Morbi eget dui ullamcorper, semper magna sit amet, cursus nulla. Aenean augue dolor, varius eu orci a, efficitur auctor diam. Quisque tempor lacus dolor. Aliquam erat volutpat. Donec imperdiet pellentesque nunc, sed accumsan sem lacinia sed. In hac habitasse platea dictumst. Nam placerat odio et leo ultricies ultrices. Cras nulla lacus, maximus in risus ut, auctor auctor vestibulum.
</p>
</div>
The function I want to implement should look like this:
const getSummarizedPreview = (query, text, windowSize) => {
// query: The word that should be highlighted. It's just one word, not a phrase.
// text: Original Text.
// windowSize: The maximum length of text returned.
}
Note that the last word of the text is also vestibulum, but getSummarizedPreview smartly chose more relevant part of the text based on the frequency of the query.
I think this might be pretty complicated to implement, so any advice, pseudocode, or introduction to library that does the simliar thing would be appreciated.
Thank you.
You can use full text search of Elasticsearch. See quick intro here.
OR you can implement this feature by yourself:
Look in your original text i see it have multi paragraph ( tag). You can split it into an array, then loop all of this array elements.
In the loop, using regex like below to find count frequency of appearance of query word:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
Get element have max count.
Replace query word with highlighted query word, like: vestibulum with <mark>vestibulum</mark>
Return formatted string for display highlighted matched query word.
This is an interesting question and I am also looking for a better solution.
Am doing a (highly recommended) Javascript tutorial (http://www.newthinktank.com/2015/09/learn-javascript-one-video/) and one of the solutions doesn't work. I'm trying to change the background colour of the first paragraph, I don't get any errors and 'developer tools' shows me that the 'style' just doesn't updated. I even copied the code from the cheat-sheet and it still doesn't work. Not sure it's a version problem or just a genuine mistake (it's been viewed over 1,000,000 times so I'm sure someone would have picked up on it by now). Here's the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css'>
</head>
<body>
<div id="sampDiv">
<p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Integer feugiat in tortor at scelerisque. Aenean nulla dui, auctor sit amet dignissim et, ultrices non odio. Pellentesque luctus eu ligula id feugiat. Mauris tempus mollis est, eget elementum massa luctus eu.</p>
<p> Sed ac ipsum libero. <b>Donec et leo</b> sit amet ante posuere pretium at eu massa. Donec tincidunt <em>elementum risus</em>, nec scelerisque massa luctus vitae. Praesent blandit tincidunt orci, <b>at commodo eros</b> interdum eu.</p>
</div>
<script>
// first paragraph
var sampDiv = document.getElementById('sampDiv');
sampDiv.childNodes[0].style.backgroundColor = "#F0FFFF";
</script>
</body>
</html>
I know there are many ways to achieve this, such as:
var pElements = document.getElementsByTagName('p');
pElements[0].style.backgroundColor = "#F0FFFF";
...but I'm interested to know what is wrong. To clarify, this is the code that isn't working:
var sampDiv = document.getElementById('sampDiv');
sampDiv.childNodes[0].style.backgroundColor = "#F0FFFF";
I'm running Chrome Version 68.0.3440.106 (Official Build) (64-bit)
The problem is that the first child node is a Text node (containing the whitespace after <div id="sampDiv"> and before <p>), not an element:
var sampDiv = document.getElementById('sampDiv');
console.log(sampDiv.childNodes[0].nodeName);
<div id="sampDiv">
<p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Integer feugiat in tortor at scelerisque. Aenean nulla dui, auctor sit amet dignissim et, ultrices non odio. Pellentesque luctus eu ligula id feugiat. Mauris tempus mollis est, eget elementum massa luctus eu.</p>
<p>Sed ac ipsum libero. <b>Donec et leo</b> sit amet ante posuere pretium at eu massa. Donec tincidunt <em>elementum risus</em>, nec scelerisque massa luctus vitae. Praesent blandit tincidunt orci, <b>at commodo eros</b> interdum eu.</p>
</div>
The author should have used children, which only contains elements, instead of childNodes, which includes all types of nodes:
var sampDiv = document.getElementById('sampDiv');
sampDiv.children[0].style.backgroundColor = "#F0FFFF";
<div id="sampDiv">
<p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Integer feugiat in tortor at scelerisque. Aenean nulla dui, auctor sit amet dignissim et, ultrices non odio. Pellentesque luctus eu ligula id feugiat. Mauris tempus mollis est, eget elementum massa luctus eu.</p>
<p>Sed ac ipsum libero. <b>Donec et leo</b> sit amet ante posuere pretium at eu massa. Donec tincidunt <em>elementum risus</em>, nec scelerisque massa luctus vitae. Praesent blandit tincidunt orci, <b>at commodo eros</b> interdum eu.</p>
</div>
Although one could argue that firstElementChild would be better than children[0].
It may be that the author didn't have that whitespace and you introduced it with formatting, or the author normally runs his/her HTML through a compressor which would probably have removed it, etc., because the code works if that whitespace isn't there:
var sampDiv = document.getElementById('sampDiv');
sampDiv.childNodes[0].style.backgroundColor = "#F0FFFF";
<div id="sampDiv"><p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Integer feugiat in tortor at scelerisque. Aenean nulla dui, auctor sit amet dignissim et, ultrices non odio. Pellentesque luctus eu ligula id feugiat. Mauris tempus mollis est, eget elementum massa luctus eu.</p>
<p>Sed ac ipsum libero. <b>Donec et leo</b> sit amet ante posuere pretium at eu massa. Donec tincidunt <em>elementum risus</em>, nec scelerisque massa luctus vitae. Praesent blandit tincidunt orci, <b>at commodo eros</b> interdum eu.</p>
</div>
sampDiv.childNodes[1].style.backgroundColor = "#F0FFFF";
not childNodes[0], but childNodes[1].
Let's assume that I have the following text within a single <p>... </p>
When a user selects a couple of words within the text, lets assume the first Quisque vestibulum is selected, I get the selected text with window.getSelection().toString(); then I apply some CSS tricks, lets say I underline the text.
When the user comes back one month later, I would like to underline same text again. How can I get an exact reference for the selected text for future reference? I don't want to highlight the second Quisque vestibulum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at
dolor sit amet augue tempor venenatis vitae et nibh. Donec dignissim
fringilla fermentum. In facilisis consectetur risus. Nam vel mauris
magna, a feugiat nisl. Quisque vestibulum, neque eu tristique
tristique, tortor mauris ornare magna, at ultricies augue orci sed
enim. Nulla magna ligula, dapibus vel commodo ac, sodales ut sem. Duis
lorem massa, consectetur sed molestie eget, posuere eu magna.
Pellentesque sollicitudin mattis facilisis. Nunc pulvinar metus et
diam dignissim sit amet pellentesque metus pretium. Quisque vestibulum, maecenas vel leo
sit amet diam iaculis sollicitudin.
You could use the search() or indexOf() and store the position of the string as well as the actual selected text.
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.