Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6845131
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T00:27:46+00:00 2026-05-27T00:27:46+00:00

I really have trouble with OO coding in js. I have written a piece

  • 0

I really have trouble with OO coding in js. I have written a piece of code which rotates through 3 divs, and pauses on hover of any div. This code is just regular js using an array/json as the input. the code is a bit long so sorry about that. I just need some guidance on how I can convert this primitive code to a better form, as in OO and encap. When I tried myself I could not pass the slides array/json to my defined object. Is there a trick or guideline i can follow on how to rewrite this to a better form?

Edit – What is a good guideline to follow so I can rewrite this with objects instead of global variables and loose functions

var slideIndex = 0;
var prevIndex = 0;
var t;

function initPromo(){
sortSlides();
nextPromo();
addListeners();
}    

function addListeners(){
for(var i=0; i<slides.length; i++) 
    $(slides[i].el).hover(function(){ stopPromo(); }, function(){ resumePromo(); });
}
function resumePromo(){ startTimer(); }

function stopPromo(){ clearTimeout(t); }

function nextPromo(){
    if(slideIndex > 0 || prevIndex > 0) $(slides[prevIndex].el).css("display","none");
    $(slides[slideIndex].el).css("display","block");
    prevIndex = slideIndex;
    slideIndex = (slideIndex<slides.length-1) ? slideIndex+1 : 0;
    startTimer();
}

function startTimer(){ t = setTimeout("nextPromo()", 3000); }

function SortByWeight(a,b) { return b.weight - a.weight; }
function SortByWeightFr(a,b) { return b.frWeight - a.frWeight; }

function sortSlides(){
    ($("body.en").length > 0) ? slides.sort(SortByWeight) : slides.sort(SortByWeightFr);    
}

var slides = [
{
    el:'#ps1',
    weight:1,
    frWeight:3
},
{
    el:'#ps2',
    weight:0.5,
    frWeight:6
},
{
    el:'#ps3',
    weight:4,
    frWeight:9
}
];
window.onload = function () {
    initPromo();    
};

HTML

<body class="en">
<div id="homepageSlides">
    <div id="promoSlides">
        <div id="ps1">ps1</div><div id="ps2">ps2</div><div id="ps3">ps3</div>
    </div>
</div>
</body>

Edit: Early days in OO coding, not asked in the right way

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T00:27:46+00:00Added an answer on May 27, 2026 at 12:27 am

    Well your “plain javascript” code is already taking you part way there. The first function you have defined identies the domain object: Promo.

    var Promo = function () { };

    You have actions on an instance of promo, init, start, stop, resume, etc. These can be defined on the prototype of Promo.

    Promo.prototype.init = function() {
      // ...
    };
    

    It could get a little annoying typing prototype each time, so we could bundle the prototype into a pointer that allows us a lot easier access…

    var Promo = function () { };
    (function(obj) {
    
        obj.init = function() {
            // ...
        };
    
    })(Promo.prototype);
    

    So we’ve got some structure but we need to now separate concerns. Throughout your plain javascript you’ve got config type data strewn through the code. It’s generally a good idea to isolate these bits of data to a single entry point for your object.

    obj.init = function(_el) {
         // where _el is the base element of this widget
    };
    

    I see you’re also using jQuery which is good because it gives you a lot of power. One convention I like to use is instead of passing a huge amount of config data into a given widget, I like to give my objects minimal config and let them inspect the HTML to determine additional configuration data. This has the added advantage of if you wanted to add slides in the future or otherwise make changes to the slide content you need’nt worry about changing the JS.

    Let’s say we were to alter the slide HTML to look like…

    <div id="promoSlides">
        <div data-type="slide" data-slide-id="1">ps1</div>
        <div data-type="slide" data-slide-id="2">ps2</div>
        <div data-type="slide" data-slide-id="3">ps3</div>
    </div>
    

    Using jQuery we could identify how many slides are present.

    obj.init = function(_el) {
        this.baseElement = $(_el);
        this.slides = this.baseElement.find('*[data-type="slide"]');
    };
    

    Now we’re passing in minimal config, we’ve separated out the identification of the slides to the HTML, and we’ve got a nice pattern for a self-sufficient object. The rest would be to fill in the details (totally untested, but something like this)…

    var Promo = function () { };
    (function (obj) {
    
        obj.init = function(_el, _delay) {
    
            // Initialize markup
            this.baseElement = $(_el);
            this.slides = this.baseElement.find('*[data-type="slide"]');
            this.slideDelay = _delay;
    
            // Sort slides
            // (not sure what's going on here)
    
            // Bind events
            this.baseElement
                .on('mouseenter', this.stop.bind(this))
                .on('mouseleave', this.start.bind(this));
        };
    
        obj.start = function() {
            this.timer = setInterval(this.advance.bind(this), this.slideDelay);
        };
    
        obj.stop = function() {
            clearInterval(this.timer);
        };
    
        obj.advance = function() {
            // Slide the visible slide off screen
            // (note: the parent tag will need overflow:hidden)
            var visible = this.baseElement.find('*[data-type="slide"]:visible');
            visible.animate({ left: '-' + (visible.width()) + 'px' }, 1000);
            // Slide the next slide in
            var next = visible.next();
            next.css('left', this.baseElement.width() + 1).animate({ left: '0' }, 1000);
        };
    
    })(Promo.prototype);
    

    Note that I made use of bind which isn’t supported yet in older versions of IE.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some trouble coding a themes shortcode. I want the code to display
I'm really having trouble with Allocatable array. I have to copy all information from
I am trying to understand if I really have any case for using git/mercurial.
I have written a JAXL daemon in PHP (Debian 6.0) which sits and listens
I really have big problems with importing an extern C-Library to my existing C++-Project.
Do I really have to learn Objective-C to develop solid Mac Apps? As Mac
It doesn't really have to add newlines, just something readable. Anything better than this?
I have a couple of projects hosted on Codeplex. Since I didn't really have
Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and
Let's say we have two objects. Furthermore, let's assume that they really have no

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.