Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code.

       <script type="text/javascript">
        $(function() {
            $('ul.nav a').bind('click',function(event){
                var $anchor = $(this);
                /*
                if you want to use one of the easing effects:
                $('html, body').stop().animate({
                    scrollLeft: $($anchor.attr('href')).offset().left
                }, 1500,'easeInOutExpo');
                 */
                $('html, body').stop().animate({
                    scrollLeft: $($anchor.attr('href')).offset().left
                }, 1000);
                event.preventDefault();
            });
        });
    </script>

I am trying to click on a navigation link (refer to Screenshot). It should scroll to the vertical red line (main DIV with class "#incontent"). However, when clicking on the "Home" link, it scrolls to the end of the site instead (Screenshot on the left side).

Can anyone provide assistance? I have limited skills in JavaScript and can't seem to find a solution.

UPDATE: Current Code:

Hello, thank you for your prompt response!

I attempted your suggested solution but it still isn't functioning correctly. I inserted

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
within

Perhaps I could share the entire code here as I am working with Joomla.

The PHP index file:

<div id="content">
<div id="incontent" class="test">
<div id="breadcrumbs"> <jdoc:include type="modules" name="breadcrumbs" style="xhtml">
</div>
           <jdoc:include type="message" />
    <jdoc:include type="component" />
</div>
</div>



<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script type="text/javascript">
         $(function() {
     var winWidth = $(window).width(),
         containerWidth = $('.test').width(),
         leftOff = (winWidth - containerWidth)/2;
     $('ul.nav a').on('click',function(event){
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollLeft: $($anchor.attr('href')).offset().left - leftOff
        }, 1000);
        event.preventDefault();
    });
    });
</script>

CSS

#incontent{
font-family: 'Raleway', sans-serif;
padding-top: 170px;
width: 6000px;
font-size: 12px;
font-weight: lighter;
line-height: 17px;
}

.items-row{
margin-left: 0px !important;
width:840px;
float: left;
background-color: #E5E5E5;
padding: 20px;
margin: 10px;
margin-top:;
border: 1px dashed #cfcfcf;
outline: 2px solid #E5E5E5;
min-height: 320px;
}

JOOMLA WYSIWYG:

<table border="0">
<tbody>
<tr>
<td class="kat">
<div id="buttons">
<ul class="nav">
<li><a href="#home">Home</a></li>
|
<li><a href="#ueberuns">Über uns</a></li>
</ul>
</div>
 </td>
</tr>
<tr>
<td>
 <p><img src="images/fotolia_38533929.jpg" border="0" width="300" height="215"    style="float: right; margin-left: 10px; margin-right: 10px;" /></p>
 <div id="home" class="ultimativ"> </div>
 <h2>Herzlich Willkommen!</h2>
  <p>Haben Sie schon länger keine Familienfotos mehr gemacht oder wollen Sie gerne schöne Fotos von Sich an dem schönsten Ort ihrer Stadt machen? Durch jahrelanger Erfahrung ist eine Vielzahl an Fotoshootings durch unsere Kameralinsen gewandert und hat vielen Freude bereitet, egal ob Studiofotos, Fotos für Ihre Hochzeitseinladungskarten oder ein außergewöhnliches Bewerbungsfoto. Klicken Sie sich durch unsere verschiedenen Bereiche und machen Sie sich ein Bild davon, wie auch ihre Bilder aussehen könnten.</p>
</td>
</tr>
</tbody>
</table>

I suspect that my issue lies in the CSS "width: 6000px", as I require horizontal space for Joomla to insert blog posts inside. I'm unsure how else to address this.


I am still encountering a bug here.

xxx

On the index page, there are two Divs

On the Print Page, there are three divs xxx

I set the width to 6000px so I can add more blog posts that automatically display inline.

But here's the issue, with 6000px everywhere, I can scroll too far to the right, causing my blog post to disappear.

I hope this is clear. I still need help with this problem!

Answer №1

Not sure about the specifics of your HTLM/CSS, but you should be able to understand the logic at least.

 $(function() {
     var winWidth = $(window).width(),
         containerWidth = $('.container').width(),
         leftOff = (winWidth - containerWidth)/2;
     $('ul.nav a').on('click',function(event){
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollLeft: $($anchor.attr('href')).offset().left - leftOff
        }, 1000);
        event.preventDefault();
    });
});

I'm calculating the difference between window width and container width (to determine spacing on each side of the container) and then dividing by 2 to get only one space.

Now that we know the width of the left space, we subtract it from offset().left of the div

$($anchor.attr('href')).offset().left - leftOff
to achieve this:

Demo

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

Issues with passing Angular directive attributes to the scope were encountered

I am having an issue with my angular directives where the arguments are not being passed into the scope: app.directive('sectionLeft', function() { return { restrict:'E', scope: { sectionContent: '=', s ...

Run a jQuery script after the form has been submitted

I need help with executing a jQuery script after submitting a form. The jQuery script is simple, just one line that will fade in a hidden to indicate whether the email was successfully sent or not. The PHP code is currently at the top of the file. I&apos ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Child functional component does not refresh after its props are altered by its parent component

Looking at the following code: MainParentComponent.js let data = 0; function MainParentComponent() { function handleClick() { data++; } return (<> <button onClick={handleClick}>Increase</button> < ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

The 1st DIV element nudges the content within the 2nd DIV Element, causing it to stretch beyond the screen with 100%

I have gone through several other questions, but I am struggling to integrate the solutions into my problem. My main content DIV is set to 100% height and works perfectly fine until I add another element outside of the DIV towards the top of the browser. ...

Utilizing Astro Project to gather content from various directories containing Markdown files

I am embarking on a project to convert Mark Down files (MD) into HTML format. While delving into this endeavor, I have chosen to utilize Astro due to its compatibility with MD to HTML conversion, even though I am relatively new to ASTRO or JSX style coding ...

A step-by-step guide on incorporating a dynamic data series into a line chart using the powerful tool

The data retrieved from a webservice is processed using the BindTrend method and then converted to a JSON object before being applied to the chart. The code for this process is as follows: var plot; var itemdata = []; var chart; var data = [] ...

The challenge of multi-level sortable lists in jQuery and Internet Explorer

Greetings to the Stack Overflow community, Unfortunately, I encountered a compatibility issue with Internet Explorer when utilizing the jQuery library along with Ajax. The problem at hand can be observed in my live demonstration: Try sorting the items i ...

How can you adjust the width of the Material UI Select component?

Trying to customize the width of the Material UI Select component can be a bit tricky. To set the desired width, you need to assign a specific class to the FormControl component. This class, such as mw-120, should define the minimum width as 120px in your ...

Explore a personalized color scheme within MUI themes to enhance your design

I'm looking to customize the colors in my theme for specific categories within my application. I set up a theme and am utilizing it in my component like this: theme.tsx import { createTheme, Theme } from '@mui/material/styles' import { red ...

instructions on how to showcase a text message within the fontawesome square icon

Can someone help me with styling my code? I want to display a text message inside a square box with dimensions of 1x. <span class="fa-stack fa-5x" style="margin-left:5%"> <i class="fa fa-square-o fa-stack-2x"></i> </span> ...

Disable text input in Flatpickr and remove the default iPhone calendar

We are facing an issue with the iPhone and iPad when using flatpickr for our calendars. When the calendar is opened, the cursor automatically focuses on the text box, triggering the default iPhone calendar to appear below. This problem does not occur on An ...

The latest version of Next.js, Version 12, encounters an issue with theme-ui that results in the error message "code: 'ERR_REQUIRE_ESM'"

Encountering an error while working with Next.js 12 after creating a theme using theme-ui. https://i.stack.imgur.com/BtH7W.png Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\ind ...

The download attribute in HTML5 is functioning properly, however it is causing a redirection to

Is it possible to use the HTML5 download attribute with a URL without being redirected to a new page? Here is the code I am currently using: exportToPdf: function(e) { var link = document.createElement('a'); link.href = 'https://filegener ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

XSLT - Dividing table into three columns while maintaining continuity on the same page

I'm looking for a solution where I can display a long two column table in a three-column page layout. The table should seamlessly flow from one column to the next, maintaining its headers throughout. Current attempts show the entire table in just one ...

Interconnected HTML div values impacting one another

Forgive me for the not-so-great title, as I am unsure of what this particular HTML coding method is called. That's why I am asking this question in the first place. I've written some code and I need to know what type of coding practice this is. ...