I have a very wide div with a lot of elements. When I press a button, I want it to come into view? $anchorscroll doesn't seem to work this way is there anything I can use?
Something for horizontal scrolling to an element
Here you go:
var app = angular.module("sa", []);
app.controller("FooController", function($scope) {
$scope.scrollH = function() {
var parent = document.querySelector("#parent");
var focusable = document.querySelector("#focusme");
var parentLeft = parent.getBoundingClientRect().left;
var focusableLeft = focusable.getBoundingClientRect().left;
parent.scrollLeft = focusableLeft - parentLeft;
};
});
#parent {
width: 300px;
background: #ccc;
overflow: auto;
}
#child {
width: 1200px
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa" ng-controller="FooController">
<div id="parent">
<div id="child">
Etiam feugiat lorem non metus. Sed cursus turpis vitae tortor. Vestibulum volutpat, euismod vitae, posuere imperdiet, leo. Sed libero. <strong id="focusme">I need to be scroll horizontally.</strong>
</div>
</div>
Scroll horizontally
</div>
You can wrap it as a directive to make code common.
Related
Is it possible to give max-height and max-width to an image while preserving aspect ratio without using js?
For example,
I want an image to be with a height of 38px and the width auto.
If the width is higher than 200px, I want the width to be 200px and the height auto.
If it's not possible without js, does anyone have an idea how to do it with js and without resizing the image after it's already loaded?
You can nest the image in a 200x38 container, then set the max-width and max-height of the image to 100%. Here is a working snippet (I have included JS to make it interactive, but it is not necessary. Try resizing the container using the sliders):
var width = document.getElementById("width");
var height = document.getElementById("height");
var widthInput = document.getElementById("widthInput");
var heightInput = document.getElementById("heightInput");
var imageContainer = document.querySelector("div");
widthInput.addEventListener("input", function() {
width.innerHTML = this.value + "px";
imageContainer.style.width = this.value + "px";
});
heightInput.addEventListener("input", function() {
height.innerHTML = this.value + "px";
imageContainer.style.height = this.value + "px";
});
div {
width: 200px;
height: 200px;
border: 1px dashed #000;
}
.image {
display: block;
max-width: 100%;
max-height: 100%;
background: #333;
}
<div>
<img class="image" src="https://via.placeholder.com/400"/>
</div>
<br/>
<label>Width: <span id="width">200px</span></label>
<br/>
<input id="widthInput" type="range" min="0" max="400"/>
<br/>
<label>Height: <span id="height">200px</span></label>
<br/>
<input id="heightInput" type="range" min="0" max="400"/>
You can notice that however you change the dimensions of the container, the image is still contained within it. By setting the container to 200px wide by 38px tall, you can force the image to stay within the limits 0px ≤ width ≤ 200px and 0px ≤ height ≤ 38px.
There is a built in CSS style called max-width and max-height and I really do not think min-width exists, incase you are wondering. You can refer to the example below to understand better. Also I am using text instead of an image, but you should get the idea.
I have nested the actual div instead another div so you could play around with the resizing.
#con {
resize: both;
overflow: auto;
}
#box {
/*Here you could say auto instead*/
height: 200px;
max-width: 200px;
}
<!DOCTYPE html />
<html>
<head></head>
<body>
<div id="con">
<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus dapibus auctor ipsum, in convallis mi lobortis in. Phasellus molestie suscipit rutrum. Duis et convallis lectus. Etiam id urna massa. Nulla sagittis erat nec arcu rutrum elementum. Vestibulum blandit erat vestibulum, ullamcorper augue vitae, accumsan mi. Sed consectetur, quam vel efficitur interdum, ante ligula interdum justo, a dictum ligula tortor sed nunc. Cras eget magna ac urna imperdiet laoreet eget sed ante. Vivamus condimentum tortor sit amet diam elementum malesuada sed sed neque. Vestibulum et magna mollis, consequat nibh ut, facilisis orci. Phasellus fermentum sodales libero, et vehicula enim ornare ut. Donec non bibendum metus. Cras hendrerit, quam a pellentesque varius, tortor nunc maximus lectus, at gravida diam ipsum ut metus. Etiam orci felis, dapibus id cursus eu, dapibus ut augue. Proin a leo viverra, tempus ipsum nec, lacinia lacus. Maecenas id dolor nec neque lobortis interdum quis quis nisi.</div>
</div>
</body>
</html>
Using both width auto and height auto will give to following code. To center horizontal I used the align-items center of the flexbox.
.container,
.container * {
box-sizing: border-box;
}
.container {
display: flex;
width: 800px;
margin: 10px auto;
}
.img {
display: flex;
align-items: center;
width: 25%;
height: 150px;
border: 2px solid silver;
}
.img img {
display: block;
border: 0;
width: auto;
max-width: 100%;
height: auto;
max-height: 100%;
margin: auto;
}
<div class="container">
<div class="img">
<img src="http://placekitten.com/200/300" alt="">
</div>
<div class="img">
<img src="http://placekitten.com/300/200" alt="">
</div>
<div class="img">
<img src="http://placekitten.com/250/350" alt="">
</div>
<div class="img">
<img src="http://placekitten.com/350/200" alt="">
</div>
</div>
You have to use max-width and height and object-fit CSS properties for image.. see example
.img img {
max-width: 200px;
height: 38px;
object-fit: contain;
object-position: left;
}
<div class="img"><img src="https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png"></div>
Hope it works... if any question comment pls
Here are 2 examples of the solution I think would work, the first image has less than width: 200px; and the second one has more than width: 200px;
Again, I'm not sure if it would work for you, but I think it would, and if it doesn't I would love to know why.
<style>
img {
max-width: 200px;
height: auto;
}
</style>
<img src="https://dummyimage.com/180x400/666/fff.jpg" alt="test">
<br>
<img src="https://images.pexels.com/photos/5686476/pexels-photo-5686476.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" alt="test 2">
Specifying height or width will keep the aspect ratio. Specifying both the max-height and max-width will keep the aspect ratio. Specifying height and max-height makes no sense. Specifying height and max-width cannot guarantee your aspect ratio.
I'm looking for a way to highlight the current html element on mouse-hover (not a specific object, anything the user encounters)
and when the user clicks the item I want to copy the content of the current html element.
How can I do that in Javascript? is there a library that I can use?
Thank you
To add a hover effect, just add a :hover rule to your CSS sylings and add the changes in style to it. No need for JS at all. In the below example, the background color changes on hover.
Same thing can be done for any element on the page by adding the css rule to the <body> tag instead of a specific object:
body *:hover { background-color: steelblue; }
To add the click event, use JS to add an click listener to either all the items, or to the container of the items. innerHTML will then give you the 'content' of the HTML node that you can do anything with. In the example below, we just send the content to another function that will log it to the console.
You could write all of this into one statement, but it's usually preferred to break these things down into small pieces so you can mix n match later on when changes are needed.
var addClick = function( callback ) {
document.querySelector( '#list_items' ).addEventListener( 'click', function( event ) {
var item = event.target;
if ( item.nodeName === 'LI' ) callback( item.innerHTML );
} );
};
var event_handler = function( content ) {
console.log( 'the content of the clicked item is: ' + content );
};
addClick( event_handler );
.list-item {
background-color: white;
border: 1px solid black;
margin-bottom: 4px;
padding: 4px;
}
.list-item:hover {
background-color: steelblue;
}
<ul id="list_items">
<li class="list-item">Item 1</li>
<li class="list-item">Item 2</li>
<li class="list-item">Item 3</li>
<li class="list-item">Item 4</li>
</ul>
This is a way we can do this.
var elements = document.querySelectorAll(".reader");
var elementArray = [...elements]
elementArray.map(function(ele){
ele.addEventListener('mouseover', function(){
this.setAttribute("style","background:yellow");
})
ele.addEventListener('mouseleave', function(){
this.setAttribute("style","background:white");
})
ele.addEventListener('click', function(){
alert(this.innerHTML);
})
})
<html>
<div class="reader">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse hendrerit, quam id viverra molestie, augue sapien hendrerit nisl, sed fermentum ante elit porta risus.
</div>
<p class="reader">
Nulla tincidunt tempor tempus. Pellentesque sed nisi eget felis pulvinar sagittis. Maecenas id erat iaculis, tincidunt urna eu, viverra metus. Pellentesque in libero auctor turpis tempor mollis.
</p>
<p class="reader">
Quisque vitae felis nisi. Praesent hendrerit sit amet nibh id scelerisque. Phasellus dictum, leo non sollicitudin pulvinar, arcu diam vestibulum leo, a eleifend libero enim et lorem.
</p>
<script type="text/javascript" src="script.js" charset="utf-8"></script>
</html>
document.execCommand needs a user event to work. It will not work on hover, but it will on clicks and the like (mousedown, mouseup, etc.).
It seems browsers do support it consistently now.
Check out my JSFiddle.
$('.image').hover(function () {
// will not work, no user action
$('input').select();
document.execCommand('copy');
});
$('.image').mousedown(function () {
//works
document.execCommand('copy');
});
Copy commands triggered from document.execCommand() will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. How implementations can be configured to allow write access to the clipboard is outside the scope of this specification.
If you don't like jQuery, a good alternative is clipboard.js
I'm having troubles positioning a button on a page with css. I want the button to be fixed at a certain position but when there is a lot of content on the page I want the button to move down.
Firstly I want the button at the bottom of the page when there isn't much content such as the code below which does this:
#Button
{
position: fixed;
height:90px;
width:220px;
left:16%;
top:70%;
border:none;
background:none;
}
Then when there is lots of content I want the button to move down such as the code below:
#Button
{
position: absolute;
height:90px;
width:220px;
left:16%;
padding-top:10%;
padding-bottom: 13%;
border:none;
background:none;
}
Can anyone help? I've looked online but cant make sense of it.
If you define a wrapper block element (a <div> for example) around all your content and put the <button> directly under that element, it is possible to reach the desired result with CSS only.
HTML:
<div id="wrapper">
<!-- other content goes here -->
<button id="button">Sample</button>
</div>
CSS:
#wrapper {
position: relative;
min-height: 100vh;
}
#button {
position: absolute;
bottom: 0;
}
However, I have to warn you about the fact that legacy browsers do not support the vh unit and some others show buggy behavior. Take a look at here before you implement it in your project.
I don't know your structure, but I'll try to help you.
Let's use the following markup:
<div class="parent">
<p class="texto">Your text goes here!</p>
<input type="button" value="OK" />
</div>
To solve your problem, I'd simply use a min-height in the content.
.parent .texto {
min-height: 100px;
}
In this way, the button will always be in the same position if there isn't much content. And it'll follow the height if there are lots of content.
Snippet:
.parent {
width: 200px;
padding: 5px;
border: 1px solid black;
float: left;
margin: 5px;
}
.parent .texto {
min-height: 100px;
}
<div class="parent">
<p class="texto">
Small text!
</p>
<input type="button" value="OK" />
</div>
<div class="parent">
<p class="texto">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mi urna, rhoncus vitae hendrerit ut, hendrerit a turpis. Phasellus sed rhoncus augue, eget vehicula neque. Vivamus lobortis, velit vitae maximus porttitor, erat nulla scelerisque est, nec
sagittis diam diam id nisl. Maecenas dictum lacinia dignissim. Duis eget ligula fermentum, vulputate dui sed, vestibulum ipsum. Duis non consectetur dolor. Nunc urna eros, tincidunt id nisl id, dapibus imperdiet orci. Mauris posuere convallis ullamcorper.
</p>
<input type="button" value="OK" />
</div>
Hope it helps!
use position:relative for the element which you have defined before this button.
This question already has answers here:
Creating a textarea with auto-resize
(50 answers)
Closed 7 years ago.
How can I display all textarea rows instead of having that vertical scroll. I have tried with css using min-height and max-height and height: auto but is not working.
.form-control{
width:400px;
min-height: 100px;
max-height: 900px;
height: auto;}
I don't really know if is possible to do that with css.
Maybe is possible with native javascript so I am trying something like this
function expandtext(expand) {
while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
console.log("display all rows!")>
}
}
I find something nice here but it only increase and decrease rows , so how can I display all textarea rows without using scroll. DON'T NEED SOLUTION WITH FIXED HEIGHT, NEED SOMETHING DYNAMIC or other solutions that works only on chrome browser or only on firefox like Object.observe().
Demo
function expandtext(expand) {
while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
console.log("display all rows!") >
}
}
body {
padding: 20px;
}
.form-control {
width: 400px;
min-height: 100px;
max-height: 900px;
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class=" form-group">
<label>remove texarea scroll and display all rows</label>
<textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum
primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet
tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>
</div>
<div class=" form-group">
<label>remove texarea scroll and display all rows</label>
<textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut.</textarea>
</div>
External JSFiddle.
Simple jQuery solution is:
$(function() {
$('textarea').each(function() {
$(this).height($(this).prop('scrollHeight'));
});
});
Check Fiddle.
As you need a plain JavaScript solution, use following script that was created by User panzi. You can view the original answer here.
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init () {
var text = document.getElementById('textarea');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}
Check Fiddle Here.
No Javascript required.
You can display a no-scroll (ie. automatically re-sizing) editable text area with the following HTML and CSS:
.textarea {
width:250px;
min-height:50px;
height:auto;
border:2px solid rgba(63,63,63,1);
}
<div class="textarea" contenteditable="true">
The Mozilla Developer Network has an Autogrowing textarea example on their HTMLTextAreaElement page. You should definitely check this out if you want to stay away from CSS3 solutions that can break on older browsers.
Here is the code from the example.
The following example shows how to make a textarea really autogrow while typing.
function autoGrow(oField) {
if (oField.scrollHeight > oField.clientHeight) {
oField.style.height = oField.scrollHeight + "px";
}
}
textarea.noscrollbars {
overflow: hidden;
width: 300px;
height: 100px;
}
<form name="myForm">
<fieldset>
<legend>Your comments</legend>
<p>
<textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea>
</p>
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
</form>
Autoadjust
This example will take care of the case where you remove lines.
function autoAdjustTextArea(o) {
o.style.height = '1px'; // Prevent height from growing when deleting lines.
o.style.height = o.scrollHeight + 'px';
}
// =============================== IGNORE =====================================
// You can ignore this, this is for generating the random characters above.
var chars = '\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var randRange=function(min,max){return max==null?randRange(0,min):~~(Math.random()*(max-min)+min);}
var randChars=function(chrs,len){return len>0?chrs[randRange(chrs.length)]+randChars(chrs,len-1):'';}
// ============================== /IGNORE =====================================
// Get a reference to the text area.
var txtAra = document.getElementsByClassName('noscrollbars')[0];
// Generate some random characters of length between 150 and 300.
txtAra.value = randChars(chars,randRange(150,300));
// Trigger the event.
autoAdjustTextArea(txtAra);
textarea.noscrollbars {
overflow: hidden;
width: 400px; /** This is via your example. */
}
<form name="myForm">
<fieldset>
<legend>Your comments</legend>
<p>
<textarea class="noscrollbars" onkeyup="autoAdjustTextArea(this);"></textarea>
</p>
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
</form>
Using Jquery and some logic I have tried to do what you need.
Here is the jsfiddle;
https://jsfiddle.net/45zsdzds/
HTML:
<textarea class="myClass" id="FurnishingDetails" name="FurnishingDetails" id="FurnishingDetails"></textarea>
Javascript:
$('#FurnishingDetails').text('hello\nhello1\nhello2\nhello3\nhello4\nhello5');
String.prototype.lines = function() { return $('#FurnishingDetails').text().split(/\r*\n/); }
String.prototype.lineCount = function() { return $('#FurnishingDetails').text().lines().length; }
$('#FurnishingDetails').css('height', ($('#FurnishingDetails').text().lineCount() + 1) + 'em');
CSS:
textarea[name='FurnishingDetails']{
height:2em;
}
Used How to get the number of lines in a textarea? to add a String prototype inorder to get the linecount.
Hello I am new with JavaScript trying to find solution for my problem.
Is there any way I can live highlight my text like we do in PDF's ?
Something like this: Plunker
Relevant Code
<div class="box">
llentesque volutpat tempus eleifend. Integer viverra erat ante. Aliquam
gravida ac nibh non sollicitudin.
</div>
<button type="button">highlight</button>
I have a button which allow/enable text highlighting on click. Then I drag my mouse selecting texts will get yellow background color.
Is this possible ? Any example will really help.
Thanks
Demo
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) { });
.box span {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<div class="box">llentesque volutpat tempus eleifend. Integer viverra erat ante. Aliquam gravida ac nibh non sollicitudin.</div>
<button type="button">highlight</button>
<div class="box" style="margin-top:100px">
DEMO:
<br>llentesque volutpat tempus eleifend. Integer viverra erat ante. <span>Aliquam gravida ac nibh non sollicitudin.</span>
</div>
</div>
The Stack Overflow entry covers numerous methods for highlighting text on a page using javascript:
How to highlight text using javascript
If this isn't what you wanted, comment below.
here's a quick example that I made for you to play with. Basically you want some sort of event, I think on('input') works well here, and then check to see if there is a <span> element somewhere.
This is not a complete example of course, and could use some more work, but it should get you started.
$('#textarea').on('input', function() {
var text = $('#textarea').val();
$('#result').html(text);
if ($('#result').html().indexOf('<span>') > -1) {
$('span:not(.highlighted)').addClass('highlighted');
}
});
// Set the value initially and trigger the event.
$('#textarea').val('Hello <span>World</span>.').trigger('input');
textarea {
width: 196px;
height: 100px;
}
#result {
border: 1px solid gray;
width: 200px;
height: 200px;
overflow: scroll;
}
.highlighted {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='textarea'></textarea>
<div id='result'></div>