Search code examples
javascriptjqueryhtmlcss

jQuery how to add image from computer


I am working on a website and creating my own gallery. However there seems to be a little problem with the code. I want to add my picture from my computer so it has the right width and height. Here is the code. I tried to do cover in CSS but some images are too big and won't fit. Thank you for reading.

<script type="text/javascript">
$('#button1').click(function()
{
$('#gallery').css("background-image", 'src=C:\Users\Eigenaar\Desktop\Nieuwe map\luffy');
 //luffy serieuse kop
});  </script>

and this is my second button which works perfectly fine but also want to change because width and height problems

<script type="text/javascript">
$('#button2').click(function()
{
$('#gallery').css("background-image", "url(http://vignette3.wikia.nocookie.net/mvl/images/e/e9/Luffy-One-Piece.png/revision/latest?cb=20140221162732");
//luffy lachende kop
});  </script>

so what I want to know is how to add my own picture.


Solution

  • The image path you use shouldn't be the actual path of the image on your computer, it should be the path that the specific html file you're in would use to get to the image.

    Your link here is the problem:

    'src=C:\Users\Eigenaar\Desktop\Nieuwe map\luffy'
    

    For example, if I had a directory that contained:

    index.html
    
    img.jpg
    

    index.html could display img.jpg using src='img.jpg'.

    However, imagine I have a directory where index.html is on the same level as a directory called "images" which contains your image file, like this:

    index.html
    
    images
        img.jpg
    

    Then, in order to display the image I would use src='images/img.jpg'.

    Most of the time, people have a folder with all of their website images in the same folder as their index.html file so they can pull directly from the folder.

    Hope this helps!

    Bonus learning note:

    .. means "go up a directory". This is useful if you can't directly access the images folder from your html file. For example, if your directories looked like this:

    html
      index.html
    
    images
      img.jpg
    

    You would first have to go up a directory before entering the images folder and displaying img.jpg. Then, your file path would be src='../images/img.jpg'.