Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    image src changing

    i want to be able to click a button then my image's src will be changed
    each image filename is like 1.jpg 2.jpg 3.jpg... this function should add 1 to the number before the ".jpg"

    my code so far is:
    Code:
    <script type="text/javascript" >
     
    var a = document.getElementById('img').src;
    var b = var a + 1
    
    function right()
    {
    document.getElementById('img').src="'img/'+'var b'+'.jpg'";
     }
    </script>
    my image has src="1.jpg" by default

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    oh this is weird code. You should learn how to handle javascript variables. The "var" keyword is used for declaring a variable not for every access to it.
    Code:
    "'img/'+'var b'+'.jpg'"
    is a literal string. Every single character of this string will be assigned to .src of the image. This is clearly not what you wanted to do

    Try this instead
    Code:
    "img/" + b + ".jpg"
    Then you are reading a string from the image .src attribute. You want to add 1 to this string? Clearly not. You want to extract the current number (or store it somewhere) and increase it by 1. You'll have to rethink your code ....

  • #3
    New to the CF scene
    Join Date
    Apr 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Could you tell me how to extract the number
    how would i use parseFloat and parseInt to do this?

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Code:
    var a = document.getElementById('img').src.match(/(\d+)/)[1];

  • Users who have thanked devnull69 for this post:

    DeathCamel57 (07-18-2011)


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •