Scrolling Text in DIV on Keydown - javascript

I want to create a scroll effect on the div such that when the SPACE key is pressed, the first span moves up out of visibility and the span become visible.
HTML
<div class="scroll-div">
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
</div>
CSS
.scroll-div{
width: 150px;
height: 100px;
overflow-y: scroll;
}
JS
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
...scroll up;
}
})
PS: If it can be done with CSS alone, I would prefer that.

You must use at the end of each .
/* Your Modified Javascript */
<script language="javascript">
//Get the no of elements having the same classname.
var items = document.getElementsByClassName("item1").length;
i=0; //set a variable to get the current element.
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
//Scroll to each element on every key press
document.getElementsByClassName("item1")[i].scrollIntoView({behavior: "smooth"});
i++; //Increment the value of i to jump to next <span>
}
});
</script>
Hope this Code will Solve your issue 😊

Related

Javascript only show elements when class XY is active

This is my first post here.
i have a big problem. i am in a bootcamp, currently.
I have a site and sections
const bookmarkButton = document.querySelectorAll('.pictureBook')
bookmarkButton.forEach(function (setIt) {
setIt.addEventListener('click', () => {
setIt.classList.toggle('bookmarkChecked')
})
})
.pictureBook {
all: unset;
background-image: url(/img/bookmark-svgrepo-com.svg);
background-size: cover;
width: 100px;
height: 100px;
position: absolute;
top: -15px;
right: -10px;
cursor: pointer;
opacity: 0.5;
}
.bookmarkChecked {
opacity: 1;
}
<section class="main__section">
<h2 class="question__title">Frage</h2>
<p class="question__text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla eius
voluptatibus modi voluptates nisi quam expedita fugiat repudiandae
animi ab.
</p>
<button class="pictureBook"></button>
<button class="showanswer__btn">Antwort anzeigen</button>
<p class="answershowed hideanswer">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. A nemo
libero tempore dolore numquam dolorum sed cumque nihil explicabo
ullam.
</p>
</section>
Now i can click the bookmark "svg" and opacity gone to 100 % ( bookmark set, color black )
I have a button. and i want, only show the "classes" i added the class for bookmarked it.
I am on the Limit. Google doesn`t help. Maybe you can?
When i click another button in my footer, the site Show please only the active sections with the class bookmarkChecked.
Thank you very much.
A bookmarked button has the bookmarkChecked class. So you can use
querySelectorAll to choose only the bookmarked button.
Use forEach to loop over the list of buttons.
Inside the forEach callback get the corresponding section for each button using the closest method
Now you can hide the bookmarked section using a class to set display none.
If all this needs to happen after a button click, then do the following inside an addEventListener.

Span text wrap issue during slideToggle() animation

The problem is that while slideToggle() is animating the span tags don't have proper text wrapping. Only once the animation finishes the span content is wrapper correctly.
I am trying to add more content on button press with jQuery. Not just plop it in, but rather have some kind of animation such as what slideToggle() provides.
Is there a fix for this or how can I implement it slightly differently to avoid the content not wrapping during the animation.
Here is an example:
$('.toggle').click(function() {
$('.moreContent').slideToggle();
});
p {
max-width: 300px;
}
.hide {
display: none;
}
<p>
<span><strong>List: </strong></span>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.
<span class="hide moreContent">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle">Toggle</button>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The jump exists because in order to animate the slide the span has to have a height but it can only have a height if it is display: inline-block or display: block, which it means it will also have a width. You can see that jQuery is adding display: inline-block to the style attribute on the element while it's animated. When the animation is done, jQuery removes the style attribute and it goes back to the previous layout, i.e. inline.
I don't know what your use case is or which parts are important (e.g. is the slide animation the important part or simply that something is animated in? Must it end on a sentence? Be two lines? Etc, etc). Below are a couple of examples that might give you some ideas to explore.
First, instead of relying on jQuery to handle the animations, you can use it to toggle a class and define the animation in the CSS. The first example sets the container height to a max of 2em and overflow: hidden (so 2 lines will be shown and the rest hidden). Then, clicking the toggle button toggles the class and when the .show_all class is added, it animates the max-height property which results in a slide animation. The max-height just needs to be big enough to show whatever content might be in the container. If it's hugely variable you could set it to some large number (since it won't take up the space unless it needs it). However, you might need to tweak your animations numbers.
The second example uses opacity and sets the animation to fade the text in/out when toggle is clicked. The hidden text still takes up space, so if you didn't want that, you could play with the CSS to workaround that. Maybe give the hidden text a negative z-index and play with the margin or positioning of the toggle button.
I'm assuming you've set up a simple example so I didn't want to get too much into the details but just wanted to provide some other ways of tackling the problem.
$('.toggle').click(function() {
$('.content').toggleClass('show_all');
});
$('.toggle-fade').click(function() {
$('.showme').toggleClass('show_all');
});
p {
max-width: 300px;
line-height: 1em;
}
.content {
max-height: 2em;
overflow: hidden;
display: inline-block;
transition: max-height .5s ease-in-out;
text-wrap: none;
}
.show_all {
max-height: 10em;
height: auto;
}
.showme {
opacity: 0;
transition: opacity .3s ease-in-out;
}
.showme.show_all {
opacity: 1;
}
<p>
<span><strong>List: </strong></span>
<span class="content">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle">Toggle</button>
</p>
<p>
<span><strong>List: </strong></span>
<span class="shown">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.</span>
<span class="showme">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle-fade">Toggle</button>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

How to add prefix for each new line in JavaScript?

I am working on a react project. I have a string that may contain newlines in it. How do I inject a symbol at the start o each line? What would be the most efficient way? (I am thinking of exploding the string into an array and adding a chat at the start of each line but that seems like a really inefficient way of doing things)
Change this
var text = "Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque";
into
var text = "> Lorem ipsum dolor sit amet,
> consectetur adipiscing elit.
> Vestibulum pellentesque"
How to add a symbol after each instance of "\n"?
Maybe you can use tagged template literals (ES6)...
Verbose version with for...of
function addPrefix(str) {
let tmp = str[0].split('\n'),
res = [];
for (const frag of tmp) {
res.push(`> ${frag}`);
}
return res.join('\n');
}
let str = addPrefix`Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
console.log(str);
One-liner with Array.prototype.map() (see Miguel's comment)
const addPrefix = str => str[0].split('\n').map(s => `> ${s}`).join('\n');
let str = addPrefix`Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
console.log(str);
To insert something at the beginning of each line of a string, use replace with the regular expression /^/gm, i.e. str.replace(/^/gm, prefix):
const Formatter = ({text, prefix}) => (
<textarea>{text.replace(/^/gm, prefix)}</textarea>
);
const text = `Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
const prefix = '> ';
ReactDOM.render(<Formatter text={text} prefix={prefix}/>, document.querySelector('div'));
textarea { font-family: monospace; width: 100%; height: 4em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div></div>

jQuery wrap closing tag until the same opening tag

I have this markup:
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora
I would like to select all the content between the closing </h2> until the next opening <h2> and wrap it as a div with a class, for example:
<h2>my title here</h2>
<div class="my-class">Lorem ipsum dolor sit amet</div>
<h2>my title here</h2>
<div class="my-class">consectetur adipisicing elit quod tempora</div>
var a = $('body').first().contents().filter(function() {
return this.nodeType == 3;
}).wrap('<div class="my-class">');
console.log(a)
.my-class{
color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora
DO something like this
$('h2').each(function(idx, elm) {
var $elm = $(elm);
// select text after h2
var next = $elm[0].nextSibling;
var val = next.nodeValue.trim();
// create div , add text to it
var $div = $('<div>');
$div.text(val);
// remove previously selected text nodes
next.remove();
// add divs after h2
$elm.after($div);
});
div {
color: blue;
font-size: 1.8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora

readmore javascript plugin first item open

I'm using this wonderful plugin and would like to know how I can set the first item to be open and the rest closed.
Any idea?
Javascript
var options = {
moreLink: '<a class="read_more_link" href="#">more...</a>',
lessLink: '<a class="read_less_link" href="#">less...</a>',
heightMargin: 50,
sectionCSS: 'display: inline-block; width: 100%;',
};
$('.content-top-wide, .content-bottom-item').each(function(){
var el = $(this), content = el.find('div:first,span:first,p:first, article:first'), maxHeight = 0;
if (content.length) {
maxHeight = content.outerHeight();
content.prevAll().each(function(){
maxHeight += $(this).outerHeight(true);
});
// set maxHeight to 200px if the element has hight greater than 200
options.maxHeight = Math.min(200, maxHeight);
el.readmore(options);
};
});
HTML
<div class="content-bottom pull-left">
<h2>Title</h2>
<div class="content-bottom-item pull-left">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus, consequatur inventore iure aliquam praesentium molestiae facilis labore! Magni, dolorem, ex? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus, consequatur inventore iure aliquam praesentium molestiae facilis labore! Magni, dolorem, ex?
</div>
</div>
Read the documentation of the plugin: https://github.com/jedfoster/Readmore.js ?
Adding "startOpen: false" to the options of the first item should solve your problem.
I managed doing this by adding an if statement:
if ( i == 0) {
options.startOpen = true;
} else {
options.startOpen = false;
}
el.readmore(options);
Here is a working version in case someone need: http://jsfiddle.net/brunodd/pvZ8H/

Categories