my question is a short one but I couldn't figure it out by myself. I've got a function like -> / . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more plex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more plex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Share Improve this question asked Mar 1, 2012 at 14:16 user1211117user1211117 31 silver badge3 bronze badges8 Answers
Reset to default 3Because the toggleText
function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick
function doesn't reference anything.
Either have the function like here http://jsfiddle/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready
state you can do the following and remove the onclick
action all together
http://jsfiddle/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery
, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
Js Fiddle
This is the solution - http://jsfiddle/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click
event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not pletly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>