Reputation: 431
I have the following script:
<!doctype HTML>
<html lang = "en">
<head>
<title>Learn jQuery</title>
<link rel = "stylesheet" href = "CSS/style.css">
<script type = "text/javascript" src = "scripts/java.js"></script>
<script type = "text/javascript" src = "scripts/jquery.js"></script>
</head>
<body>
<div id = "main">Click to Show and Hide <button id = "btnA">+</button></div>
<div id = "box">Some content.</div>
<script>
$(document).ready(function()
{
$("#btnA").click(function()
{
$("#box").slideToggle(2000);
// code block in question
if (val == "+")
{
$(this).html("-");
}
else if (val == "-")
{
$(this).html("+");
}
});
});
</script>
</body>
</html>
I wish to transform the code block in question
into a re-usable function like this:
function toggleContent(target, contentA, contentB)
{
var val = $(target).html();
if (val == contentA)
{
$(this).html(contentB);
}
else if (val == contentB)
{
$(this).html(contentA);
}
}
However when I call toggleContent("#btnA", "+", "-");
, it doesn't work. Could someone point out my error? TIA.
The suggested changes so far does not work, even the DEMO
. Could someone help?
Upvotes: 0
Views: 590
Reputation: 2094
Arkadiusz G's comment may give you the answer.
Change
function toggleContent(target, contentA, contentB)
{
var val = $(target).html();
if (val == contentA)
{
$(this).html(contentB);
}
else if (val == contentB)
{
$(this).html(contentA);
}
}
To
function toggleContent(target, contentA, contentB)
{
var val = $(target).html();
if (val == contentA)
{
$(target).html(contentB);
}
else if (val == contentB)
{
$(target).html(contentA);
}
}
UPDATE
And also add this
$(function(e){
$('body').on('click','#btnA','',function(){
toggleContent("#btnA", "+", "-");
});
});
Upvotes: 1
Reputation: 369
Inside the function "toggleContent", the "this" object is not what you think, try this way:
function toggleContent(target, contentA, contentB)
{
var val = $(target).html();
if (val == contentA)
{
$(target).html(contentB);
}
else if (val == contentB)
{
$(target).html(contentA);
}
}
Upvotes: 1
Reputation: 3922
Hi if you want to convert it to function pass currentObj also to the function.
function toggleContent(currentObj,target, contentA, contentB)
{
var val = $(target).html();
if (val == contentA)
{
currentObj.html(contentB);
}
else if (val == contentB)
{
currentObj.html(contentA);
}
}
toggleContent($(this), $("#btnA"), "contentA", "contentB")
Upvotes: 0