I'm new to javascript and i put together a little code with jquery to open a floating div relative to another. Problem is i don't know what i'm doing wrong, i keep getting 'opendiv is not defined' $(document).ready(function(){ var img = $("#myPic"); var pos = img.position(); function opendiv() { $(".product_desc_j").show(1000); $(".product_desc_j").css({'top' : pos.top + 25 + 'px', 'left' : pos.left + 25 + 'px'}); } function closediv() { $(".product_desc_j").hide(1000); } }); Code (markup): <div id="plm" onclick="opendiv()">click me</div> Code (markup):
I got something to work, but I'm still learning jQuery so there is probably a better way of doing it. <html> <head> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $(document).ready(function(){ var img = $('#plm'); var pos = img.position(); $('.product_desc_j').hide(); $('#plm').click(function() { $('.product_desc_j').show(1000); $('.product_desc_j').css({'top' : pos.top + 25 + 'px', 'left' : pos.left + 25 + 'px'}); }); $('.product_desc_j').click(function() { $(this).hide(1000); }); }); </script> <style type='text/css'> #plm { background-color: #0f0; height: 100; position: relateive; width: 100; } .product_desc_j { background-color: #00f; height: 100; position: absolute; width: 100; } </style> </head> <body> <div id='plm'>click me <div class='product_desc_j'></div> </div> </body> </html> Code (markup):
I think it has to do with function scope. opendiv() and closediv() are inside the jquery ready function, so they can only be called from within it. I'm not sure how you go about calling them from outside it, haven't got up to that part yet It sort of works when they are outside of the jquery ready function: <html> <head> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $(document).ready(function(){ var img = $("#myPic"); var pos = img.position(); $(".product_desc_j").hide(); }); function opendiv() { $(".product_desc_j").show(1000); $(".product_desc_j").css({'top' : pos.top + 25 + 'px', 'left' : pos.left + 25 + 'px'}); } function closediv() { $(".product_desc_j").hide(1000); } </script> <style type='text/css'> #plm { background-color: #0f0; height: 100; position: relateive; width: 100; } .product_desc_j { background-color: #00f; height: 100; position: absolute; width: 100; } </style> </head> <body> <div id="plm" onclick="opendiv()">click me<div class='product_desc_j'></div></div><br /> <div onclick="closediv()">Click To Close</div> </body> </html> Code (markup):