0

So I am creating this basic image website on php and I am trying to make an image space on each persons profile. I want the image to be maximized (as it currently is) when clicked upon. And then when clicked again it to return to its old position (which it doesn't do). you can see an example here http://www.uk-sf.com/profile.php?view=pgallery:17

but here is the code: below is the img element that is clicked

<img id="1" onclick="clickimage(this)" class="pgall" src="XXX">

then you have the javascript function

function clickimage(id)
        {
            var y = document.getElementsByClassName('pgall');
            var x = document.getElementsByClassName('pgall2');

            var length = y.length,
            element = null;
            for (var i = 0; i < length; i++) {
              element = y[i];
              element.className = 'pgall';
            }

            var length = x.length,
            element = null;
            for (var i = 0; i < length; i++) {
              element = x[i];
              element.className = 'pgall';
            }

            id.className = 'pgall2';
        }

as you can see currently it will always change what is clicked to my second CSS class "pgall2". What it needs to do is change it too "pgall" if the id.className == "pgall2". However I tried doing this with an if statement and it does not work.

                if(id.className == 'pgall')
                {
                id.className = 'pgall2';
                }
                else {
                id.className = 'pgall';
                }

1 Answers1

0

Your function doesn't add a class, it replaces the entire class value. By changing classes you're essentially creating new elements. You don't have the same event handlers available at that point.

How to properly add an additional class: How do I add a class to a given element?

More on dynamic element events: http://toddmotto.com/attaching-event-handlers-to-dynamically-created-javascript-elements


UPDATE: You have jQuery available. Why not use it?

jQuery('.pgall').click(function() {
    jQuery(this).toggleClass('pgall pgall2');
});

http://jsfiddle.net/isherwood/vPC7r/

Community
  • 1
  • 1
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • if you take a look at the site now the effect is it sticks on the name... so I end up with class="pgallpgall" – user3211248 Apr 19 '14 at 03:31
  • I don't see that. I see it change to `pgall2`. – isherwood Apr 19 '14 at 03:49
  • At any rate, you have several errors showing in the console--two apparent attempts at jQuery and a stack error. Might help to get those cleared up first. Also, you're loading a bunch of 6MB images into the page, which is a bit nuts. – isherwood Apr 19 '14 at 03:52