i want to make function with parameter. i working with below code but it is not working. can anyone tell me what am i doing wrong.
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function hide(fn){
$(fn).click(function(){
$('div').hide()
})
})
</script>
<style>
div { width:500px; height:500px; background:#FF0000; }
</style>
</head>
<body>
<button onclick="hide(this)">click for hide</button>
<a href="#">click</a>
<button>click</button>
<div></div>
</body>
One important thing: you should write unobtrusive JavaScript, as it is considered best practice. With it, you can maintain a separation of content from code. Thus, the first step is to remove that
onclickhandler on the<button>element.I’m assuming you want to click the button that says “click for hide” to hide the
<div>. Okay, so let’s get some skeleton code out into the<script>:But we need to somehow link that
clickhandler to that button, and link thathidefunction to the actualdiv. Here’s the easiest way to do this: give your<button>and<div>some ids. Let’s say…Now, we simply need to make a few modifications to our skeleton code:
Here’s what this simple code does. When your DOM loads, a nameless function (you can’t name functions that you define on the fly*) is invoked from the document’s ready event. This nameless function attaches the
clickhandler to your#hide-buttonbutton, so that when you click the button, another anonymous function is invoked. That function callshide, which does some jQuery magic that works in all browsers, on that#hide-divdiv to hide it.*Well, you can, but only if you define them first and then pass them. Like this:
Edit
Since the asker does not want to use IDs or classes, here’s an alternative solution:
Be careful not to place
function hide()within jQuery’s document-ready idiom. Doing so will deny you access tohide()because of scoping.