Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data attribute value to integer for in javascript?

I've been searching everywhere for this and can't seem to find an anwser that works. What i have is a slider with arrows and buttons, when an arrow or button is clicked the function grabs the data-cs attribute which it uses to to determine the next slide.

the html

<div id="arrowleft" class="sliderbtns flip" data-sc="prev"></div>
<div id="arrowright" class="sliderbtns" data-sc="next"></div>
<div id="buttons" class="sliderbtns">
<div class="selectedbtn sliderbtns" id="button1" data-sc="1"></div> 
<div class="button sliderbtns" data-sc="2"></div> 
</div>

the javascript

$( ".sliderbtns" ).click(function() {
    var button_data = $(this).attr('data-sc');
    myslider(button_data);
});

the function in js

function myslider(position) {
    if (position == "next" && (currentslide == slidecount)) {
        position = 1;
    } else if (position == "next") {
        position = currentslide + 1; 
    } else if ((position == "prev") && (currentslide == 1)){
        position = slidecount;
    } else if ((position == "prev")) {
        position = position - 1;
    } else { 
        // position must then eqauls some integer from the data-sc attribute
        position =  parseInt(position);
        alert (position); // alerts properly the first time
        var out_slide = "Slide" + currentslide + "Out"; 
        var next_slide = "Slide" + position;
        alert(out_slide); //these work fine the first time 
        alert(next_slide);
        window[next_slide]();        
        window[out_slide]();
        // later on in the slide currentslide becomes position after this it returns value of Nan
        setTimeout( function() {
            currentslide = position;
            alert("this is the current slide position" + currentslide);
        }, 2000);
    /* ommited code */
    }
 }

The arrows work fine if I just click on the arrows but when I click on a button it proprly goes to the next slide but none of the buttons no longer work and display current position as NaN, I have tried making the position variable an int in a bunch of different ways with Number(position), ToInt and ParseInt, but still after currentslide = position it returns it as Nan and the slider can no longer find the proper slides and functions etc... If any one has any idea what I could be doing wrong, how to properly make sure it's an actuall integer if that's posssible from a data attribute, or maybe some other way around I can throw that data around as and int that could be gotten by clicking the arrows or buttons. Greatly appreciate any help!

like image 324
Alex Avatar asked Oct 16 '25 02:10

Alex


1 Answers

To get data use .data():

 $(this).data('sc')
like image 189
Milind Anantwar Avatar answered Oct 17 '25 18:10

Milind Anantwar