Content that scrolls horizontally

I am currently working on a website that includes a section where the content needs to scroll horizontally as you click on the menu buttons. I have managed to implement the direction navigation, however, I am struggling to track the position of my divs in order to move them each time a button is clicked. I have been attempting to use offset(); with jQuery but have not been successful. Any assistance in guiding me through this process would be greatly appreciated. Below is some of the code and a link to a JS Fiddle for reference.

HTML Code:

<nav>
    <ul>
        <li id="1" class="active-state">1</li>
        <li id="2">2</li>
        <li id="3">3</li>
        <li id="4">4</li>
        <li id="5">5</li>
    </ul>
</nav>

<section id="content">
    <div id="wrapper">
        <div class="content" id="yellow"></div>
        <div class="content" id="blue"></div>
        <div class="content" id="red"></div>
        <div class="content" id="purple"></div>
        <div class="content" id="green"></div>
    </div>
</section>
<ul id="directionNav">
    <li id="left">left</li>
    <li id="right">right</li>
</ul>

jQuery Code for Horizontal Scroll:

$("#3").on("click", horizontalScroll);
$("#4").on("click", horizontalScroll2);

function horizontalScroll() {
console.log($("#3").offset().left);
$("#wrapper").animate({
    right: ($("#4").offset().left -1200)
});
console.log("clicked");
}

function horizontalScroll2() {
console.log($("#4").offset().left);
$("#wrapper").animate({
    right: ($("#4").offset().left -1200)
});
console.log("clicked");
}

Here is the JS Fiddle link for reference: http://jsfiddle.net/xtatanx/DY3k3/

Thank you for any help or insight!

Answer №1

It seems like you're overdoing it with the coding!

Make sure to give attributes to your HTML tags indicating the page they are linked to:

<li frame='1' class='nav'>page 1</li>

Then, create a single function for all .nav elements that will navigate to the designated page:

function changeFrame(){
    $('#wrapper').animate({left : $(this).attr('frame')*-600});
    $('.active-state').removeClass('active-state')
    $(this).addClass('active-state')
}

For your next/prev links, determine the current page and adjust by adding or subtracting 1. I separated this into two functions for better organization.

Upon clicking, check which link is selected:

function navigFrame(){
    switch(this.id){
        case 'left' : doNavig(-1); break;
        case 'right' : doNavig(1); break;
    }
}

Below is the code for onNavig:

function doNavig(direction){
    var newPage = parseInt($('.active-state').attr('frame'))+direction;
    if(newPage < $('.nav').length && newPage >= 0){
        $('#wrapper').animate({left : newPage*-600});
        $('.active-state').removeClass('active-state')
        $('.nav:nth-child('+String(newPage + 1)+')').addClass('active-state')
    }
}

The code could be more efficient, but I challenge you to optimize it further :)

Here's the full code snippet for reference: http://jsfiddle.net/DY3k3/2/

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

Which is the better option: replacing content with Ajax loading or appending content?

Currently, I am working on developing a predominantly ajax-driven website where content is fetched based on hashTag changes. However, I am facing a dilemma between two options: Option 1 In this option, the content is replaced with each request. Option 2 ...

Tips for ensuring consistent sizing of card items using flexbox CSS

I'm attempting to create a list with consistent item sizes, regardless of the content inside each card. I have experimented with the following CSS: .GridContainer { display: flex; flex-wrap: wrap; justify-content: space-around; align-item ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Jquery Autocomplete has the ability to store and recall previous user selections

When the region is selected, autocomplete addresses should be displayed. Each time the region changes, the Jquery autocomplete function is called. While I am able to get the correct autocomplete addresses for the current region, I also receive address list ...

Guiding users who have disabled JavaScript through redirection

When faced with the following markup, users whose browser has JavaScript disabled will be redirected to an alternative page. This alternate page may attempt to mimic the site's functionality without JavaScript or simply display a warning message infor ...

Leveraging a combination of directives alongside a primary directive

Our application currently utilizes angular-redactor.js from https://github.com/TylerGarlick/angular-redactor. The objective is to develop a new angular directive capable of accommodating any text editor, not limited to redactor. Is there a method to call ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

The "ID" value for the row that was chosen is unable to be parsed with AJAX JQUERY

After populating an HTML table with data retrieved from a database using PHP, I encountered an issue while trying to fetch the correct ID using AJAX. Following a recommendation to use classes to build my jQuery code, I find myself stuck and unsure of what ...

Is there an issue with the vertical alignment of two adjacent empty inline blocks?

body { border: 2px solid black; height: 100px; } div { vertical-align: middle; display: inline-block; width: 50px; height: 50px; } .a { border: 2px solid red; margin-top: 20px; } .b { border: 2px solid green; } <!DOCTYPE html> & ...

Is it possible to target a dynamically inserted p tag along with its child button using JavaScript?

I have a dynamically added paragraph element within a div that is already in the DOM. My goal is to use the button inside the paragraph to remove the entire paragraph itself. <div class="prime_ben"> <p class=”beneficiary”> ADDED: John C Sm ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Trouble with the AutoComplete feature in jQuery version 1.9.1

I am currently using jQuery version 1.9.1 and encountering an issue with autocomplete implementation. I am populating the autocomplete values through a JSON ajax call. However, when I try to use the autocomplete event, it is not functioning correctly and ...

Nested components knockout knockout knockout! The $(document).ready() function fires off before the nested component is even loaded

I am faced with a situation where I have multiple nested knockout components in my code: <component1> <component2> .... </component2> </component1> The issue here is that while component1 is custom-made by me, component2 ...

Utilizing Compass SCSS with Blueprint for Optimal Overflow Settings

I've been working with blueprint through Compass, but I'm facing an issue where longer pages don't have scroll bars. It seems like the default setting for overflow is 'hidden'. Since this appears to be the standard, I assume there ...

Scraping Websites with SimpleHTMLDom in PHP

I am struggling to extract specific data from a table on a website page, particularly the columns name, level, and experience. The table's alternating row colors (zebra pattern) are complicating this task. I have implemented SimpleHTMLDom for this pu ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

retrieve user input from various angular 6 components

Currently, I am in the process of developing a small web-based game using Angular 6. Within this project, I have two key components - play.component and setup.component. The main concept is to allow users to customize elements such as difficulty within the ...

Assigning a specific width to a div element will override the float property of the div

I encountered an issue while trying to position the divs titled "menu" and "content" side by side. Initially, they were placed correctly until I decided to set their width using % instead of px. After making this adjustment, the 'float: left;' pr ...

Incorrect color change on button triggered by onMouse actions and state fluctuations

While creating a user profile on my app, I encountered an issue with button coloring. When I try to add color functionality to the button, it turns red instead of green and remains red even when the mouse is not hovering over it. My goal is to have the but ...

Using jquery to remove textbox value when checkbox is unchecked

I have a single datatable created using jQuery. The first column of the table consists of checkboxes, and the last column contains textboxes. Because these elements are generated dynamically, they end up having identical IDs and names as shown below: $ ...