Rafał Developer
Rafał Developer

Reputation: 2055

hide .img javascript onload

Why this code does not work correct? I searching .img attribute but style is not changing and always picture is visible.

HTML

    <script type="text/javascript">
    function displayDate()
    {
            $('img[alt=image2]').css("display","none");
            $('img[alt=image3]').css("display","none");
            $('img[alt=image4]').css("display","none");

            $('img[alt=image2]').css("visibility","visible");
            $('img[alt=image3]').css("visibility","visible");
            $('img[alt=image4]').css("visibility","visible");
    }
</script>

HTML

<body OnLoad="displayDate()">
<img src="im.jpg" alt="image2"/>
<img src="im.jpg" alt="image3"/>
<img src="im.jpg" alt="image4"/>
</body>

you can see error in chrome

enter image description here

Upvotes: 0

Views: 1537

Answers (2)

huysentruitw
huysentruitw

Reputation: 28141

I think your problem is that you don't have the jQuery library included while you are using jQuery syntax. So try to include the jQuery library by adding this to the <head> of your page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

The jQuery way to execute something on load is like this:

$(function() {
   // this code will execute on load
});

The jQuery way to hide an element is like this:

$('img[alt="image2"]').hide();

To hide the images that have an alt containing the word 'image' you can do this (other selector options can be found here):

$(function() {
    $('img[alt*="image"]').hide();
});

Instead of using the alt attribute, an other option is to assign a class to the images, so you can select the images depending on their class:

$(function() {
    $('.myImageClassName').hide();
});

<img class="myImageClassName" />

or to wrap them in a div with a unique id:

$(function() {
    $('#myImageContainer img').hide();
});

<div id="myImageContainer">
    <img />
    <img />
    <img />
</div>

Upvotes: 4

user1846747
user1846747

Reputation:

Just try having an id for each img tag and try using this jquery hide() function...

$('#your_img_id').hide();

might work...

Upvotes: 1

Related Questions