Implementing the IF statement in jQuery

I've been trying to implement an overflow check when hovering over a div. The issue arises because I'm using jQuery for the hover function and then simple JavaScript for the overflow check in the next step. It seems that directly using an if-then statement inside a jQuery function does not work as intended. However, I still need the action to trigger the if-then statement when hovering over the div. Can someone provide assistance with this? =)

So the flow is jQuery (hover) -> JS (check overflow) -> jQuery (add to div (in this case: "...read more..."))

HTML:

<div class="hover_cap">
<div class="hcd">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum 
</div>
</div>

CSS:

.hover_cap {
   width:150px;
   max-height: 17.5ex;
   border: 1px solid red;
}

.hcd {
    line-height:2.5ex;
    max-height:12.5ex;
    margin: 10px;
    border: 1px solid green;
    overflow: hidden;
}

.readmore {
  padding: 0px 10px 10px 10px;
}

JS:

$('.hover_cap').hover(
  
  // Check for overflow condition
  if (function checkOverflow(hcd) {
      var curOverflow = hcd.style.overflow;

      if (!curOverflow || curOverflow === "hidden") hcd.style.overflow = "visible";

      var isOverflowing = hcd.clientWidth < hcd.scrollWidth || hcd.clientHeight < hcd.scrollHeight;

      hcd.style.overflow = curOverflow;

      return isOverflowing;
    }) {

    // Execute these functions when hovering over the div
    function() {
      $(this).append($('<a>...read more...</a>'));
    },
    function() {
      $(this).find("a:last").remove();
    }
  }
}

Answer №1

Check out this code snippet: When you move your mouse over the parent div, a 'readmore' button will be added to it if the child div's text is too long. If you move your mouse away from the parent div, the 'readmore' button will be removed.

function checkOverflow(element){
    return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}

$(document).ready(function(){
  $('.hover_cap').hover(function(){
    var $this = $(this);
    var $textContainer = $this.find('.hcd');
    $textContainer.css('overflow','auto');
    var isOverflowing = checkOverflow($textContainer[0]);
     $textContainer.css('overflow','hidden');
    if(isOverflowing) {
      $this.append($('<a>...read more...</a>'));
    }
  }, function(){
    var $this = $(this);
    var lastA = $this.find("a:last");
    if(lastA) {
      lastA.remove();
    }
  })
})
.hover_cap {
   width:150px;
   max-height: 17.5ex;
   border: 1px solid red;
}

.hcd {
    line-height:2.5ex;
    max-height:12.5ex;
    margin: 10px;
    border: 1px solid green;
    overflow: hidden;
}

.readmore {
  padding: 0px 10px 10px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hover_cap">
<div class="hcd">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum 
</div>
</div>

<br/>
<br/>

<div class="hover_cap">
<div class="hcd">
Short text, no overflow
</div>
</div>

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

Node.js is known for its ability to export both reference and pointer values

Having an issue with exporting my routing table from my express application. In the /bin/www.js file, there is a global variable representing the routing table: var routingTable = []; To create a simple route, new routing objects are pushed using the se ...

Encountering a 403 Forbidden error in CodeIgniter 3 when sending a POST request asynchronously using jQuery.ajax()

I am encountering a 403 forbidden error when making a jQuery.ajax() post request. application/config/config.php $config['csrf_protection'] = TRUE; $config['csrf_token_name'] = 'csrf_ghive'; $config['csrf_cookie_name&apos ...

To access a restricted selection of images stored in Firebase

Is there a way to load additional images from Firebase by clicking a button? I created a function that looks like this: onLoadMore() { if (this.all.length > 1 ) { const lastLoadedPost = _.last(this.all); const lastLoadedPostKey = lastLoadedP ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

When using the ngFor directive, the select tag with ngModel does not correctly select options based on the specified

Issue with select dropdown not pre-selecting values in ngFor based on ngModel. Take a look at the relevant component and html code: testArr = [ { id : '1', value: 'one' }, { id : '2', ...

Collapsed Bootstrap 5 select drop-down featuring the multiple attribute

I am facing a challenge with using the select element along with the 'multiple' attribute. My aim is to have it collapsed by default and expand only when the user clicks on it. Unfortunately, Bootstrap 5 no longer supports the multiselect feature ...

Tips for eliminating null values from a JavaScript object

I am currently facing an issue with a JavaScript object that consists of two arrays. At times, one of the arrays might be empty. I am attempting to iterate through the object using a recursive function, but I want to exclude any empty arrays or strings fro ...

Posting an array using jQuery's AJAX feature

Consider the following JavaScript array structure: testarr = new Array(); testarr[0] = new Array(); testarr[0]["#FFFFFF"] = "White"; testarr[0]["#FFFFFF"] = new Array(); testarr[0]["#FFFFFF"]["#FFFFFA"] = "A"; testarr[0]["#FFFFFF"]["#FFFFFB"] = "B"; test ...

Tips for creating a dashed border line that animates in a clockwise direction when hovering

I currently have a dashed border around my div element: .dash_border{ border: dashed; stroke: 2px; margin:20px; } My goal is to make the dashed lines move clockwise when my pointer hovers over the div element and stop moving ...

Unable to retrieve JSON data from the given URL

Here is the JSON data I have: { "status": "ok", "count": 1, "data": { "6217895": { "clan": { "role_i18n": "Saha Komutanı", "clan_id": 16682, "role": "commander", ...

React and Material-Ui utilize class definitions in .js files, which are then passed as strings to components

I am attempting to define a class within my .js file in order to utilize the material-ui theme object and pass it as a string to a component since the component's prop only accepts strings. Unfortunately, the React-Dropzone import does not accept a cl ...

Calculating the sum of all elements in an array

Hi, I am currently attempting to retrieve the total value from an array (such as Arr[1] + Arr[2], and so forth). Unfortunately, I am struggling to find a solution. Below is my existing function: this.hourlyTotals = function() { var custsperhour = Math ...

Inadequate speed and efficiency in Javascript and JQuery operations

I'm facing severe lag problems in my JavaScript code, particularly with the parallax effects being very slow. I suspect this is due to multiple executions of functions. Below is the code snippet: function tada() { $(".arrow").addClass("tada"); s ...

When utilizing the .populate() method in Mongoose, how can you retrieve and append ObjectIds with extra attributes to an array (which is returned by .populate()) collected from the

When using the .populate() method in Mongoose, how can I retrieve and add ObjectIds with additional properties to an array (returned by .populate()) if their corresponding document in the collection no longer exists? This question pertains to MongoDB and ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Unable to download file from Express using res.download in Angular

Within my application, I am generating a file on the backend and then attempting to provide it to the user for download via a browser. Despite multiple attempts, I have been unable to achieve this. Below is the code snippet for the express backend: app.g ...

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

Tips for avoiding the freezing of bootstrap-select scroll when a large number of options are present

I have integrated a bootstrap-select with a total of 1000 options. However, I am encountering an issue where when I attempt to scroll down the list of options, it only goes down approximately 60 options and then freezes in that position. Can anyone provi ...

Obtain the parent element using the specified id

I currently have a table with the following structure: <tr> <td id="id">2</td> <td id="type"><span class="label">snippets</span></td> <td id="name">all</td> ...