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).

https://i.sstatic.net/7yXkv.jpg

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

Navigating sub-domains swiftly

Having trouble setting up sub-domains and routing in Express Node. I need to direct users based on their device and browser type. If the user is on a desktop, they should be routed to web.. If they are on a mobile device, it should be mobile.. And if the ...

Issues with Ajax response causing PHP and HTML submit button to not function properly

When I have an input on my webpage that is linked with AJAX, it searches for a name in the database and returns the result as an HTML form with values from the database. However, the submit button within the form is not functioning properly. Here is a sni ...

invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below: <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> ...

The battle between percentages and pixels in fluid design

I am looking to create a flexible layout and would like to achieve the following: width:100%-200px; This means having a div that contains content, referred to as div id="content", with a fixed margin on each side. I have attempted to place the div id="co ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

TypeAhead.js and Bloodhound displaying an uneven quantity of search outcomes

I have a frontend setup with TypeAhead and Bloodhound integration, fetching JSON data from a Play/Scala server. The version of Typeahead being used is 0.11.1. Here is how the implementation looks: HTML: <div id="typeahead" class="col-md-8"> < ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

CodeIgniter Flexi Auth - Redirect users promptly upon login expiration

Is it possible to use the CodeIgniter Flexi Auth library to redirect a user to the login page immediately upon session expiration, displaying a message stating: "Your login has expired, please login again," rather than waiting until page load? I'm co ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Store the token securely in your browser's localStorage and set up interceptors

Struggling with saving the token in localStorage and pushing it in interceptors to send it with all requests. Currently, passing user data and token from Symfony controller to frontend, but facing roadblocks in saving the token in localStorage and settin ...

Saving an image and form data together in local storage can be accomplished by using JavaScript

Is there a way to save an image to local storage along with form data? I would like to store the form data in a database and keep the image in local storage. Any help would be greatly appreciated. Thank you! <form id="saveImageForm"><input type ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code: $('img').each(function() { var pageInfo = {}; var img_src = $(this).attr('s ...

Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads: "TypeError: Cannot read property 'push' of undefined" at r.$scope.addGroup (main.js:7) at fn (eval at compile (angular ...

Adjust the size using padding alone

My CSS specifies font size of 14px, line height of 14px, and padding of 7px on the top and bottom. The total should be 28px. When I apply these styles in a div, it results in a height of 28px. However, when applied to a ul li a element, the height becomes ...

JavaScript code for initiating the npm start command

Is it possible to include the npm-start command in a JavaScript script? Requirement: Develop a JS script capable of triggering the npm-start command. Operating System: Microsoft Windows I need to turn it into a Windows service. However, in the code snip ...

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Incorporate a new substance into a THREEJS Mesh

Is there a way to add a material to an existing mesh without calling the mesh constructor again? I already have a mesh created using the constructor: var mesh = new THREE.Mesh(geometry, material); Now I have created another material in my code: ...