Ways to integrate jQuery's .hover() with Overflow

I've hit a roadblock and can't seem to find the solution on my own. Hopefully, someone out there can provide me with a hint.

I am trying to meet the following requirements:

  • There should be a Newsblock within an HTML Page with a fixed width and height.
  • Within this Newsblock, only the titles of the news should be visible.
  • These news items should start off as "collapsed" by default and expand when the mouse is hovered over them.
  • Since the 'Newsblock' has a limited height, a scrollbar should appear if the expanded news exceeds the block's height, allowing users to scroll down.
  • The Newstitle and Newstext should always remain within the Newsblock.

So far, I have been able to fulfill all of these requirements except for the one regarding the Scrollbar. Whenever I try to access the Scrollbar while hovering over the currently expanded news, it collapses again and the Scrollbar disappears. It seems that my .hover function is set up to SlideUp whenever I leave the newsentry, causing the Scrollbar to vanish since it is not part of the newsentry div. I'm unsure about what changes I need to make in order to maintain an overall Scrollbar for the Newsblock without it disappearing when trying to reach it.

P.s.: Having a separate Scrollbar per Newsentry would look odd. That's why I want to somehow 'bind' the scrollbar to the parent container :S

HTML

    <div id="newsblock">
        <div> // There are some auto-generated divs that I have to work with, so the news entries are not direct children of the news block.
            <div class="newsentry">
                <div class="newstitle">...</div>
                <div class="newstext">...</div>
            </div>
        ... another 9 'newsentry' divs.
        </div>
    </div>

JS

    $(".newsentry").hover(
        function() {
            $(this).children(".newstext").stop(true,true).slideDown();
        },
        function() {
            $(this).children(".newstext").stop(true,true).slideUp();
        }
    );

CSS

    .newsblock {
        height: 200px;
        overflow-y: auto;
    }

Answer №1

One way to handle the closing of a .newsentry is to implement a solution where it closes only when entering another .newsentry or leaving #newsblock. By considering the scrollbar as part of #newsblock, the entry will not close anymore when hovering over it.

UPDATE: After discussing the scroll problem, I incorporated a step callback into the closing animation to ensure that the top of the opened .newsentry remains visible while other entries are being closed.

Below is a functional demonstration:

var $newsblock = $("#newsblock");

function closeAllNews(slideUpArgs){
    return $(".newstext").stop(true).slideUp(slideUpArgs);
}

function openNews(news, slideDownArgs){
    $(news).find(".newstext").stop(true).slideDown(slideDownArgs);
}

function ensureNewsTopVisible(news){
  // Check if the top of the newsentry is visible...
  var top = $(news).position().top;
  if(top < 0){
    // ...and if not, scroll newsblock accordingly.
    $newsblock.scrollTop($newsblock.scrollTop() + top);
  }
}

$(".newsentry").each(function(){
    var $this = $(this);
    // When the mouse enter a news entry...
    $this.on("mouseenter", function(){
        // ...close all opened entries (normally there is at most one)...
        closeAllNews({
          // (while making sure that the top of this entry remains visible
          // at each step)
          step: ensureNewsTopVisible.bind(null, $this)
        });
        // ...open this newsentry.
        openNews($this);
    });
});

// When the mouse get out of the newsblock, close all news.
$newsblock.on("mouseleave", closeAllNews);
.newstitle {
    font-size: 2em;
}
.newstext {
    display: none;
}
#newsblock {
    max-height: 150px;
    overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="newsblock">
    <div>
        <div class="newsentry">
            <div class="newstitle">News 1</div>
            <div class="newstext"></div>
        </div>
        <div class="newsentry">
            <div class="newstitle">News 2</div>
            <div class="newstext"></div>
        </div>
        <div class="newsentry">
            <div class="newstitle">News 3</div>
            <div class="newstext"></div>
        </div>
        <!-- Etc. -->
    </div>
</div>


<!-- Ignore the script below. It is just filling in the news' text. -->
<script>
  $(".newstext").each(function(i, newstext){
    $.get("http://baconipsum.com/api/?type=meat-and-filler&format=html&paras=5&num=" + i)
      .then(function(ipsumHtml){
        $(newstext).html(ipsumHtml);
      });
  });
</script>

Answer №2

Give this a try:

$(".newsentry, .newsblock").hover( // <-- updated
        function() {
            $(this).children(".newstext").stop(true,true).slideDown();
        },
        function() {
            $(this).children(".newstext").stop(true,true).slideUp();
        }
    );

This code ensures that the block remains open when hovering over either the header or the block itself.

Does that match what you're looking for?

Answer №3

Imagine this scenario: There's a joke, and if I happen to be incorrect... all you need to do is adjust your CSS like so:

/* not .newsblock **/
      #newsblock {
                height: 200px;
                overflow-y: scroll; /* not auto */
            }

Answer №4

Using click operations instead of hover to slide down news text blocks can greatly improve user experience. When hovering, users may accidentally trigger the scroll bar instead of viewing the news content. Implementing an accordion-like functionality could be a solution. Here is a sample code for achieving this using click events:

$(".newsentry").click(
        function() {
            $(".newstext").stop(true,true).slideUp();
            $(this).children(".newstext").stop(true,true).slideDown();
        }
    );

Alternatively, you can stick with hover by using the following code:

$(".newsentry").hover(
    function() {
        $(".newstext").stop(true,true).slideUp();
        $(this).children(".newstext").stop(true,true).slideDown();
    },
    function(){}
);

This approach ensures that the news text block remains open until the user hovers over another news entry.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to arrange buttons next to each other?

Here is the code for a specific page: HTML: <div class=main> <div class=bttn> <button>abcdef</div> <div class=content> <a href=#!>jksg</a> <a href=#!>jksg</a> & ...

Trouble encountered in aligning two DIVs in a horizontal position

I have been through numerous discussions on the same problem, but none of the solutions seem to work in my case. I am currently working on a section of my website that has 3 small boxes, each containing an image on top and text below. The issue arises when ...

Tips for placing text alongside a logo while maintaining navigation links on the right side

I am a beginner in the world of CSS and have been working on a practice project. However, I am struggling to achieve what the title suggests. I attempted using the margin-right: auto method that I've learned from various tutorials, but it only ends u ...

Having difficulty determining the file type of a user-uploaded file on the front-end

I am looking to organize files into separate folders based on their file type using the multer module. However, I am encountering an issue where the fileType constant variable is undefined in the multer disk storage setup, even though it is correctly acces ...

Merge the inverse property and inverse class selector with the current selector for enhanced specificity

I was looking at this jQuery code snippet: $("#Filter ul input:checked").each(function () { if (!$(this).prop("disabled") && !$(this).hasClass("ignoreInput")) { Is there a way to simplify this into just one selector? It seems like I'm ha ...

Is it possible to retrieve a (escaped) HTML attribute from an XML node using XPath?

In this scenario, the XML node labeled 'description' includes HTML that has been escaped. My goal is to extract the src attribute from the first img tag. Is there a method in XPath to accomplish this task? <item> <description>&am ...

Leverage jquery-ui for enhanced functionality in portal version 8

After successfully implementing jQuery in Websphere Portal 8 by following this article, I now have a new question. How can I incorporate jQuery-UI into Websphere Portal 8? My concern is that jQuery-UI comes with multiple JS and CSS files, so I am unsure ...

Difficulties involving AJAX requests in Firefox and Internet Explorer

My checkbox triggers an AJAX request whenever its state changes (checked/unchecked). Everything was working fine when I tested in Chrome. But when I tried using Firefox or IE, the AJAX request wasn't updating the value in the SQL server. I'm a b ...

ng-if not functioning properly in Internet Explorer 8

Currently, I am developing a substantial Angular application that needs to be compatible with IE8. However, we are encountering performance problems as we implement ng-show extensively on the homepage. I am considering using ng-if to completely remove pa ...

Error message: "Encountered 'Cannot Get' error while building Angular

I encountered an error when trying to run my Angular project in IntelliJ. Upon opening the browser on localhost, I received the message Cannot GET / Here are the steps I followed: Opened up the project Ran npm install -g @angular/cli@latest Ran gradlew c ...

Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly: $('#ddl').change(function () { $('#cont').html(''); var count = getCount($('#ddl').val()) for (var i = 0; i < count ; ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

Having trouble getting a resizable DIV inside a 100% height DIV with margin to work properly. Any tips or assistance would be greatly

I've encountered a common issue that is slightly different from others I've come across. Despite my best efforts, I have been unable to find a solution on my own. If anyone could offer me some guidance on this, I would greatly appreciate it. The ...

How can we capture the current row's value for later retrieval?

Using datatables to display data from a mySQL database, I am looking to extract the current row's value and present it in a modal for editing. This is how the data is integrated into Datatable: $(document).ready(function() { $(' ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...

Bootstrap 4.3 is not designed with a mobile-first approach in mind

I'm currently in the process of creating a bootstrap component for one of my clients' websites. They are still utilizing Bootstrap 4.3. Despite Bootstrap's mobile-first design philosophy, I noticed that when I examine my development site, it ...

What could be the reason for the failure of @babel/preset-react automatic transformation with Webpack?

The setup involves a Yarn monorepo with a babel.config.js that specifies the environment. React version being used is 18.1.x. I have a similar configuration that works perfectly fine in another setup, but it's failing here. I've been painstaking ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

Different CSS values can be applied for specific versions of Internet Explorer by using conditional comments

I am dealing with a CSS class named "myclass" that requires a z-index of 5 specifically for IE8. I have attempted to achieve this using the following methods: .myclass{ z-index: 5\9; } ---> Interestingly, this method applies from IE10 onwards a ...

Why isn't my heading showing up as expected in my document?

Can anyone help me understand why my title appears so low on certain screens? I've previously tried removing the negative margin when the title was hidden, but now it's positioned too far down. Here is the link to my webpage: ...