focusing on the child element of the current event's target

As I was working on a project, I came across a tab-menu jQuery plugin that needed some modifications. The issue I encountered was that the tabs were absolutely positioned, causing them to be taken out of the flow and not contribute to the wrapping div's height, thus hiding the background behind them. To solve this problem, I attempted to dynamically adjust the height of the wrapping div (which contains the background image) to match the selected tab's height (+400px for navigation and header). In order to achieve this, I made some changes to the original jQuery file and added a few lines which are marked as 'added!'. Here is the modified code snippet:

var cbpHorizontalMenu = (function () {
    var $listItems = $('#cbp-hrmenu > ul > li'),
        $menuItems = $listItems.children('a'),
        $body = $('body'),
        current = -1;

    function init() {
        $menuItems.on('click', open);
        $listItems.on('click', function (event) {
            event.stopPropagation();
        });
    }

    function open(event) {
        if (current !== -1) {
            $listItems.eq(current).removeClass('cbp-hropen');
        }
        var $item = $(event.currentTarget).parent('li'),
            idx = $item.index();
        if (current === idx) {
            $item.removeClass('cbp-hropen');
            //added!
            current = -1;
        } else {
            $item.addClass('cbp-hropen');
            current = idx;
            $body.off('click').on('click', close);
            var content2Height = jQuery(".cbp-hrsub").height() + 400;
            jQuery('#content2').height(content2Height); //added
        }
        return false;
    }

    function close(event) {
        $listItems.eq(current).removeClass('cbp-hropen');
        //added!
        current = -1;
    }
    return {
        init: init
    };
})();

The current implementation partially meets my requirements. However, it retrieves the height of the first div.cbp-hrsub element and applies it (plus 400px) to the div.content2. My goal is to target the height of the currently selected tab (presumably a child of event.currentTarget), calculate its height, and apply it to the content2 div.

To provide context, here is a simplified version of the HTML structure:

<div class="content2">
<nav id="cbp-hrmenu" class="cbp-hrmenu">
    <ul>
        <li>
            <a href="#">tab 1</a>
            <div class="cbp-hrsub">
                <div class="cbp-hrsub-inner"> 
                    I am the 1st tab, with a height of 100px.
                </div>
            </div>
        </li>
        <li>
            <a href="#">tab 2</a>
            <div class="cbp-hrsub">
                <div class="cbp-hrsub-inner">
                    I am the 2nd tab, with a height of 200px.

                </div>
            </div>
        </li>
        <li>
            <a href="#" class="white06">Nigel's CV</a>
            <div class="cbp-hrsub">
                <div class="cbp-hrsub-inner"> 
                    I am the 3rd tab, with a height of 300px.
                </div>
            </div>
        </li>

    </ul>
</nav>

Just to clarify, I intend to retain the original functionality of the plugin and simply replace my two additional lines towards the end of the script. (

var content2Height = jQuery(".cbp-hrsub").height() + 400; jQuery('#content2').height(content2Height); //added
) Thank you to everyone who takes the time to read and assist.

Zel

Answer №1

Whenever I attempt to target a parent container using .parent(), the outcomes are inconsistent. This code snippet illustrates the issue:

var $item = $(event.currentTarget).parent('li'),
        idx = $item.index();

An alternative approach is to utilize .closest() instead:

var $item = $(event.currentTarget).closest('li'),
        idx = $item.index();

However, upon closer inspection, I have identified the problem:

var content2Height = jQuery(".cbp-hrsub").height() + 400;

By selecting all elements with the .cbp-hrsub class, jQuery will compute a height based on these elements. It may simply choose the first element from the array.

What you actually require is something similar to this:

var content2Height = $item.first(".cbp-hrsub").height() + 400;

This modification will accurately determine the height of the .cbp-hrsub within the current item, rather than relying on the first element in the array.

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

"Extracting regular expressions between the penultimate and ultimate characters

I'm struggling with a simple regex question. I want to extract text between two specific characters: - and ~ Here's my string: Champions tour - To Win1 - To Win2 ~JIM FURYK Currently, when I use this regex pattern: \-([^)]+\~), it mat ...

How can you display Unicode characters within an HTML input element with type=submit value?

I am having trouble displaying a right facing triangle character after the main text on a form button based on a designer mockup. The code snippet causing issues is as follows: <input type="submit" value="Add to basket &#9654;" /> The desir ...

Ways to make a div adjust to the width of its content

Hello, this is my first time posting a question here. I have found many helpful Java answers in this community before, so I thought I'd give it a try. I did some research beforehand, but please let me know if I have duplicated a question or done anyth ...

Leveraging an external script for enhanced functionality in React/Meteor application

I'm currently facing a challenge incorporating an external script into my React component within Meteor. I've experimented with directly placing the script tag in my component as follows: TheLounge = React.createClass({ render() { return ( ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

Implementing a blur effect on a CSS loader

I have successfully implemented a loader feature where a loading animation is displayed upon clicking the submit button, indicating that the form submission is in progress. However, I am encountering an issue when trying to apply a blur effect to the entir ...

Utilizing a React hook within an event listener

I have developed a custom hook for playing audio in react, here is the code: "use client"; import { useEffect, useState } from "react"; export const useAudio = (url: string) => { const [audio, setAudio] = useState<HTMLAudioE ...

Utilizing JQuery to ensure that rows have consistent height in two dynamically generated tables

To meet my specific requirements, I am tasked with creating two separate tables that will contain the same number of rows but different data. The first table will display Item Information, while the second table will provide consolidated information about ...

Dynamically align text in the center of an image, vertically

I'm trying to create a hover effect where an image and text are displayed in the center of the image when someone hovers over it. Here is how the HTML looks: <article> <div class="entry-content"> <a href="http://www.linktopost.com"> ...

Ways to stop a webpage from auto-refreshing using JAVASCRIPT

While working on a form to submit values using AJAX and PHP, I encountered an issue where the return value of AJAX was always 0. After some investigation, I realized that the problem was caused by the page being refreshed. AJAX var xhttp = new XMLHttpRequ ...

Failure to send chat form

I have been developing a PHP chat application and everything is working well. However, I am looking to implement AJAX in order to prevent the page from refreshing. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></s ...

Is the user currently viewing this page?

My website, www.mysite.com, has a basic login system using PHP and MYSQL. With the $_SESSION['user_id'] in place, I am wondering if there is a way to determine if a user currently has the page www.mysite.com/test.php open. Is it possible to acco ...

Restricting the ability to uncheck jQueryCheckboxes

I have a unique scenario where I have two forms located in different tabs. Each crossover field has the ability to duplicate its value to the other form when there is a change in the field's content. In addition, I have implemented a feature where th ...

Eliminate the focus border in React-Select

I've been struggling to remove the border or outline (not really sure which one it is) from React Select when it's focused. Here is an image for reference. As you can see, I currently have no default border: https://i.stack.imgur.com/IubaN.png ...

How to delete URL parameters in JavaScript and HTML5

I have a URL that looks like this: /users/?i=0&p=90 How can I remove the part from ? to 90 Can anyone provide me with some JavaScript code to achieve this? EDIT I mean doing this with window.location.href directly in the browser URL bar. I trie ...

What sets apart initializing an Express app using "app = new Express()" compared to "app = express()"?

Throughout my experience, express apps have always been initialized like this: var express = require('express') var app = express() However, today I came across an example where a new operator was used: var Express = require('express&apos ...

Fetching Data Sequentially with a Delay using AJAX and jQuery in PHP

As a newcomer to Jquery, I am looking for a way to showcase data in a sequential manner using AJAX. Imagine there is a table called "DATA" in my database with a field named "info" containing multiple rows of information. info 1 2 3 4 5 My goal is to exh ...

Positioning of buttons in Bootstrap 5 tables

I am working on a table that represents a CRUD application with details of a person and edit/delete buttons. The goal is to have these buttons displayed side by side, even on smaller screen sizes where they currently stack on top of each other. How can I ...

The functionality of react-router-dom's NavLink isActive feature seems to be unreliable

We are currently immersed in a React.js project. I am in the process of setting up multiple pages using react-router-dom and my goal is to alter the active icon by using NavLink. The icon+sel signifies the active page. render() { const oddEvent = (mat ...

issue with ajax or database functionality

I've been facing a challenge for quite some time now. I'm trying to make an AJAX callback by setting an input field, but I can't seem to get it right. Below is the code snippet: Script $('[name="acccode[]"]').each(function(idx,v ...