How to set tooltips in qml text - qt

Is there some way to show a tip when I hover some word in my qml text? For examle I want to see a definiton of the word I hovered in a text.
*Wikipedia website has this feature.

To allow hovering over individual words, you can use this code:
import QtQuick
import QtQuick.Controls
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
HoverHandler {
id: hoverHandler
onHoveredChanged: {
if (hovered)
toolTip.hide()
}
}
Label {
id: label
anchors.fill: parent
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
wrapMode: Label.Wrap
onLinkHovered: (link) => {
if (link.length === 0)
return
// Show the ToolTip at the mouse cursor, plus some margins so the mouse doesn't get in the way.
toolTip.x = hoverHandler.point.position.x + 8
toolTip.y = hoverHandler.point.position.y + 8
toolTip.show(link)
}
}
ToolTip {
id: toolTip
}
}
It uses Text's linkHovered signal to respond to links being hovered, and HoverHandler to ensure that the ToolTip is hidden when a link isn't hovered. You could also pass a timeout to show() to hide the ToolTip after a certain amount of time, but that's less user-friendly.
The style used in the GIF is the Material style.

I understood that the OP asked to hover a certain word inside a Text.
The following is an alternative to Mitch's answer that supports hovering not only links. With some overhead though.
You can use Grid, Repeater and ListModel.
Example:
import QtQuick 2.15
import QtQuick.Controls 2.15
Rectangle {
anchors.fill: parent;
Grid {
spacing: 10
anchors.centerIn: parent;
Repeater {
anchors.fill: parent;
model: ListModel {
ListElement {
text: "lorem"
tip: ""
}
ListElement {
text: "ipsum"
tip: ""
}
ListElement {
text: "I have a tip"
tip: "Never pee to the pool you drink from"
color: "red"
}
ListElement {
text: "dolor"
tip: ""
}
ListElement {
text: "amet"
tip: ""
}
}
delegate:
Text {
text: model.text
color: model.color
MouseArea {
id: _mouseArea
hoverEnabled: true
anchors.fill: parent
}
ToolTip.visible: _mouseArea.containsMouse && model.tip;
ToolTip.text: model.tip
}
}
}
}
You can easily create C++ / Python model that will fill these roles based on a plain string.
If you want to create your own custom tooltip check this SO and this Github repository or this Github repository.

Mitch's answer depends on the hover event being free to propagate to the HoverHandler, and we've been having second thoughts about https://codereview.qt-project.org/c/qt/qtdeclarative/+/420965/ But I think since the accepted flag exists, it's nice to be able to use it. And since https://codereview.qt-project.org/c/qt/qtdeclarative/+/400979 we have ruled out some cases, such as having an Item with a HoverHandler that is under or over the item of interest (the Text or Label) without being a child or a parent of it. We might have to change our minds about that if we find too many cases that are too hard to achieve; time will tell.
Since we say that QML is a declarative languge, I'm always looking for ways to write it more declaratively, with less JavaScript. So here's a more-declarative version of Mitch's answer, which also avoids the propagation problem:
import QtQuick
import QtQuick.Controls
ApplicationWindow {
title: label.hoveredLink.length > 0 ? "hovered link" : hoverHandler.hovered ? "hovered text" : "not hovered"
width: 640
height: 480
visible: true
Label {
id: label
anchors.fill: parent
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
wrapMode: Label.Wrap
onHoveredLinkChanged: (link) => {
if (link.length > 0) {
toolTip.x = hoverHandler.point.position.x + 8
toolTip.y = hoverHandler.point.position.y + 8
}
}
HoverHandler { id: hoverHandler }
}
ToolTip {
id: toolTip
visible: label.hoveredLink.length > 0
text: label.hoveredLink
}
}
The reason that there's still a JS snippet in onHoveredLinkChanged is to fix the tooltip position at the time that you hover. If you don't mind it following the cursor while the link is hovered, you can write it fully declaratively, and as a self-contained component:
import QtQuick
import QtQuick.Controls
Text {
id: textItem
width: 480; height: 240
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
wrapMode: Text.WordWrap
HoverHandler { id: hoverHandler }
ToolTip {
id: toolTip
visible: text.length > 0
text: textItem.hoveredLink
x: hoverHandler.point.position.x + 8
y: hoverHandler.point.position.y + 8
}
}
I think we are missing some functionality that would make it nicer to find hovered words. QtQuick's Text doesn't even have a function to hit-test and find the text cursor position for a pixel position (although we do have linkAt(x, y)); that would be a good start. I have wanted something like that for language learning for years: be able to look up any word that I hover in some sort of dictionary; so that would be nice to have.

Related

change Accordion.Header style in React bootstrap

I started using react Bootstrap and I'm trying to change the background-color of my accordion and also take the focus off when I click on it, but I'm not getting it. How can I change accordion style?
Here is my code:
import { Accordion} from 'react-bootstrap';
import './App.css';
function App() {
return (
<>
<Accordion>
<Accordion.Item eventKey="0">
<Accordion.Header style={{ backgroundColor: '#343a40' }}>Accordion Item #1</Accordion.Header>
<Accordion.Body>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</Accordion.Body>
</Accordion.Item>
</Accordion>
</>
);
}
export default App;
.accordion-button {
background-color: gray !important;
}
.accordion-button:focus {
box-shadow: none;
}
.accordion-button:not(.collapsed) {
color: #212529;
}
https://codesandbox.io/s/optimistic-lalande-ojusme

QML: Wrap Text to height when using RichText

I'm trying to display a long(ish) HTML file in a QML Text object.
When the text is longer than can be displayed in the current viewport, it gets chopped off
(i.e. only half of the last line of text is shown and the bottom half is hidden).
Ordinarily, I'd use elide or maximumLineCount, but none of those properties work when using Rich Text.
Since this is a full HTML document it has to be RichText not StyledText.
Example:
Rectangle {
width: 300;
height: 400;
Text {
id: text
anchors.fill: parent
textFormat: Text.RichText
wrapMode: Text.Wrap
text: "..."
}
}
What kind of properties/changes could I add to either the Text or the Rectangle to make it only show the text that can be shown in the given width and height?
The only other question related to this one that I could find was Qml: use Text's elide property with textFormat: RichText, but that wasn't practical in my case.
You'd be better wrapping your Text component inside a container like ScrollView. Flickable is another alternative.
ScrollView {
width: 300
height: 400
clip: true
Text {
id: text
textFormat: Text.RichText
text: "..."
}
}
Or... if you really want to put the text inside a Rectagle and clip its content, then simply set clip property of your Rectangle to true.
Rectangle {
width: 300
height: 400
clip: true
Text {
}
}
I am still looking for a better solution than below. With better I don't mean something that would do a binary search, instead of shrinking from the end.
var paras = content.text.match(/<p(.*?)>.*?<\/p>/g);
if (content.contentHeight > content.height) {
for (let i = paras.length - 1; i >= 0; i--) {
let para = paras[i];
let words = para.replace('</p>','').split(' ');
for (let j = words.length - 1; j >= 0; j--) {
paras[i] = words.slice(0, j).join(' ') + '</p>';
content.text = paras.join('');
if (content.contentHeight <= content.height) break;
}
if (content.contentHeight <= content.height) break;
}
}
From CSS: Can you prevent overflow: hidden from cutting-off the last line of text? and QML Text: how to use CSS properties, e.g. text-decoration: overline I tried if the solution below could work as text property. Only later to find out column-width not being supported (yet) in QT.
<html>
<body>
<div style=\"width: 1168px; height: 576px; overflow: hidden;\">
<div style=\"column-width: 1168px; -webkit-column-width:1168px; height: 576px;\">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<body>
</html>

How to delete the content that are out of a div size

I have a parent div with a certain size and inside him I have other divs and if any of those child divs start showing their content out of the parent div I want to delete that div, and no I don't want to put it hidden with the overflow I really want to delete him. I tried to search the solution but I didn't found any. How can I manage this problem?
I have this JSFiddle to a better understading the problem.
Here is the code:
<div style="width: 300px; height: 55px; background-color: gray">
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div style="border: 2px solid red">
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <strong>I WANT DO DELETE THIS DIV!</strong>
</div>
</div>
I don't know if I can do this with Blazor but I'm here to learn.
Thank you for your attention.
Basically you can do this by looping over the children, and checking if their top corner is “higher” on the Y axis (“higher” value on that axis meaning, it is lower down on the screen), than the parent’s own height. You can use the offsetTop property here, if the parent element is also the offsetParent of the children - if positioning is involved anywhere, that might change the offsetParent, so in that case you might need to work with coordinates relative to the viewport.
var p = document.getElementById('parent'),
c = p.children;
for(var i=c.length-1; i>=0; --i) {
console.log(c[i], c[i].offsetTop, p.offsetHeight)
if(c[i].offsetTop >= p.offsetHeight || c[i].offsetHeight > p.offsetHeight) {
p.removeChild(c[i]);
}
}
#parent { position: relative; }
foo
<br>
<div id="parent" style="width: 300px; height: 55px; background-color: gray">
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div style="border: 2px solid red">
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <strong>I WANT DO DELETE THIS DIV!</strong>
</div>
</div>
I am looping over the children in reverse order here - that gives less hassle with removing elements, and the index of the remaining elements in the live HTMLCollection returned by children.
I introduced the foo<br> at the beginning here, so that the whole element is set off a bit from the viewport - then you’ll notice how setting the parent to position:relative changes the offsetTop values, remove that from the CSS and see how the values in the debug output change.
Now this is a trivial way to do this, based on your rather trivial example. In more complex layout situations, it might not work that easily.
Edit: Need to check not only the offsetTop, but the offsetHeight as well. Otherwise, the last element might not get removed, if it is higher than the parent itself.
you need to add a css attribute overflow : hidden
See more: https://developer.mozilla.org/fr/docs/Web/CSS/overflow
I think this will work.. Try this code..
css
div div:not(:first-child) {
display: none;
}

max-width capped at 75%

It took me like 20 minutes to find this, so I'm asking and answering my question.
So, say I have a div:
<div id="foo"> Lorem ipsum dolor sit amet consecuter Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div>
And I'm not sure how much stuff is in the div. It could be one sentence or an entire scientific article.
So, if there's not much in the div, I want it to be just as wide as it needs to be. But, if there's a lot of stuff in the div, I want it to be, say, width: 75%.
I.e., if it fits within 75% of your browser window, it's one line. If it doesn't fit, the lines wrap at 75%.
How do I do this?
Easy peasy.
#foo {
width: max-content;
max-width: 75%;
}
So if the content fits within 75% of your broswer window, It'll be on one line. If it doesn't fit, it'll line wrap at 75%.
If your browser doesn't support max-width yet, it will pin at 75%, which is fine.
An overcomplicated jsfiddle example doohickey:
var data;
var delay = 150;
async function thingy() {
$("#controls").hide();
$("#magic").text("");
var i;
for (i = 0; i < data.length; i++) {
$("#magic").append(data[i] + " ");
await sleep(delay);
}
$("#controls").delay(1000).fadeIn();
}
function updatedelay() {
$("#delay").text(delay + "ms");
}
$(function() {
data = $("#data").text().split(" ");
thingy();
});
// grrrr
// Credit: http://stackoverflow.com/a/39914235/2729876
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
#magic {
border: solid 1px black;
padding: 10px;
margin: auto;
width: max-content;
max-width: 75%;
}
#controls {
display: none;
border: solid 1px blue;
width: 50%
}
#data {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<div id="magic"> </div>
<br><br><br>
<div id="controls">
<button onclick="thingy();">Again!</button>
<br><br>
Delay:<span id="delay">150ms</span><br>
<button onclick="$('#delay').text((delay+=100)+'ms')">++</button>
<button onclick="$('#delay').text((delay+=10)+'ms')">+</button> |
<button onclick="$('#delay').text((delay-=10)+'ms')">-</button>
<button onclick="$('#delay').text((delay-=100)+'ms')">--</button>
</div>
</center>
<div id="data">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

CSS: fixed position on x-axis but not y?

Is there a way to fix a position on the x-axis only? So when a user scrolls up, the div tag will scroll up with it, but not side to side?
Its a simple technique using the script also. You can check a demo here too.
JQuery
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + 15
//Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
});
});
CSS
#header {
top: 15px;
left: 15px;
position: absolute;
}
Update Credit: #PierredeLESPINAY
As commented, to make the script support the changes in the css without having to recode them in the script. You can use the following.
var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + leftOffset //Use it later
});
});
Demo :)
This is an old thread but CSS3 has a solution.
position: sticky;
Have a look at this blog post.
Demonstration:
And this documentation.
If your block is originally positioned as static, you may want to try this
$(window).on('scroll', function () {
var $w = $(window);
$('.position-fixed-x').css('left', $w.scrollLeft());
$('.position-fixed-y').css('top', $w.scrollTop());
});
.container {
width: 1000px;
}
.position-fixed-x {
position: relative;
}
.position-fixed-y {
position: relative;
}
.blue-box {
background:blue;
width: 50px;
height: 50px;
}
.red-box {
background: red;
width: 50px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="position-fixed-y red-box">
</div>
The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do.
<div class="position-fixed-x blue-box">
</div>
DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA.
The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring.
The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer.
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism).
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein.
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created.
</div>
Now that mobile is over 70% from the internet market you can create something smart and responsive to do that.
You can create this very easy with only css, use a overflow-x:scroll for a container and a overflow-y:scroll for another container. You can easily position the container elements with width:100vw and height:100vh.
Middle click on the example to test it. Works best on mobile because you dont see the scroll bars.
body{max-width:100%}
*{box-sizing:border-box;}
.container{background:#ddd;overflow-y:scroll;width:500px;max-height:100vh;}
.header{background: pink;}
.body{background: teal;padding:20px;min-width: 100%;overflow:scroll;overflow-y:hidden;min-height:300px;}
.body >div{min-width:800px;}
<body>
<div class="container">
<div class="header">
Button 1 > Button 2 > Button 3
</div>
<div class="body">
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
</div>
</div>
</body>
No, it's not possible with pure CSS. That kind of positioning fixes the element in the viewport. I'd suggest simply fixing the element to one of the sides of the viewport (i.e. top, bottom, left or right) so that it doesn't interfere with other content.
Starx's solution was extremely helpful to me. But I had some problems when I tried to implement a vertical scrolling sidebar with it. Here was my initial code, based on what Starx wrote:
function fix_vertical_scroll(id) {
$(window).scroll(function(){
$(id).css({
'top': $(this).scrollTop() //Use it later
});
});
}
It's slightly different from Starx's solution, because I think his code is designed to allow a menu to float horizontally instead of vertically. But that's just an aside. The problem I had with the above code is that in a lot of browsers, or depending on the resource load of the computer, the menu movements would be choppy, whereas the initial css solution was nice and smooth. I attribute this to browsers being slower at firing javascript events than at implementing css.
My alternate solution to this choppiness problem is set the frame to fixed instead of absolute, then cancel out the horizontal movements using starx's method.
function float_horizontal_scroll(id) {
jQuery(window).scroll(function(){
jQuery(id).css({
'left': 0 - jQuery(this).scrollLeft()
});
});
}
#leftframe {
position:fixed;
width: 200;
}
You might say all I'm doing is trading vertical scrolling choppiness for horizontal scrolling choppiness. But the thing is, 99% of scrolling is vertical, and it's much more annoying when that is choppy than when horizontal scrolling is.
Here's my related post on this matter, if I haven't already exhausted everyone's patience: Fixing a menu in one direction in jquery
I stumbled on this post looking for a nice way to keep my header/navigation bar centered and responsive to size changes.
//CSS
.nav-container {
height: 60px; /*The static height*/
width: 100%; /*Makes it responsive to resizing the browser*/
position: fixed; /*So that it will always be in the center*/
}
//jQuery
$(window).scroll(() => {
if ($(document).scrollTop() < 60) {
$('.nav-container').css('top', $(document).scrollTop() * -1)
}
})
As we scroll, the bar moves upwards off the screen. If you scroll left/right it will stay fixed.
I realize this thread is mighty old but it helped me come up with a solution for my project.
In my case I had a header that I wanted to never be less than 1000px wide, header always on top, with content that could go unlimited right.
header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>
$(window).on('scroll resize', function () {
var header = $('header');
if ($(this).width() < header.data('min-width')) {
header.css('left', -$(this).scrollLeft());
} else {
header.css('left', '');
}
});
This also should handle when your browser is less than your headers min-width
I just added position:absolute and that solved my problem.
This is a very old thread, but I have found a pure CSS solution to this using some creative nesting. I wasn't a fan of the jQuery method at all...
Fiddle here:
https://jsfiddle.net/4jeuv5jq/
<div id="wrapper">
<div id="fixeditem">
Haha, I am a header. Nah.. Nah na na na
</div>
<div id="contentwrapper">
<div id="content">
Lorem ipsum.....
</div>
</div>
</div>
#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}
#fixeditem {
position: absolute;
}
#contentwrapper {
width: 100%;
overflow: scroll;
}
#content {
width: 1000px;
height: 2000px;
}
Updated the script to check the start position:
function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
var leftScroll = jQuery(this).scrollLeft();
if (isLeft)
el.css({ 'left': (start + leftScroll) + 'px' });
else
el.css({ 'right': (start - leftScroll) + 'px' });
});
}
If you want to fix it on the right, for example, use justify-content: flex-end.
More: http://www.w3schools.com/cssref/css3_pr_justify-content.asp
On parent div you can add
overflow-y: scroll;
overflow-x: hidden;
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + 15
//Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
});
});
Thanks
Yes, You actually can do that only by using CSS...
body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }
Tell me if it works
Very easy solution is:
window.onscroll = function (){
document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}
Sounds like you need to use position:fixed and then set the the top position to a percentage and the and either the left or the right position to a fixed unit.

Resources