Search code examples
javascripthtmlpdosliderhref

Increment, decrement href in JavaScript


I have an image gallery that I would slide by two buttons.

The values from the database:

<?php

$sql = "SELECT * FROM struttura ORDER BY id_img";
$result = $pdo->query($sql);

while ($row = $result->fetch())
{
    $id_img = $row['id_img'];
    $file = $row['file'];
    $text = $row['text'];
    ?> 
    <li><img src="images/<?php echo htmlspecialchars($file, ENT_QUOTES, 'UTF-8');?>" id="<?php echo htmlspecialchars($id_img, ENT_QUOTES, 'UTF-8');?>" /></li>
    <?php
}
?>

This is the div for navigation

<div class="navigation">
<a href="#" class="nav_prev js-shown">Prev</a>
<a href="#" class="nav_btn"></a>
<a href="#" class="nav_btn"></a>
<a href="#" class="nav_next js-shown">Next</a>
</div>

How can I increase or decrease the value of href in this way using JavaScript?

<a href="#1" class="nav_btn"></a>
<a href="#2" class="nav_btn"></a>
<a href="#3" class="nav_btn"></a>
...

Thank you in advance!


Solution

  • with pure javascript

    var link = document.getElementsByClassName('nav_btn');
    for(var i = 0; i< link.length; i++){
    
        link[i].href = '#'+(i+1);
        link[i].innerHTML = '#'+(i+1);
    
    }
    

    you can use jquery each loop

    $( function(){
    
        $('.navigation').find('.nav_btn').each(function(i){
            var $this = $(this);
            $this.attr('href','#'+i); // this will return from #0 you can this with '#'+i+1
        });
    
    } )