Hey guys i've done some research on similar questions and i tried the given solutions but i still don't get why it doesn't work.
Everyone says that you have to use the document ready
-function.
And now some solutions say that i have to remove it?
I don't really see a problem with the code.
Could someone explain clearly to me why this isn't working? I'm so curious. Thanks for the efforts.
here's the code:
$(document).ready(function(){
$('#expandSearch').css('display', 'none');
$('#easySearch').css('display', 'block');
function showExpanded(){
$('#expandSearch').css('display', 'block');
$('#easySearch').css('display', 'none');
}
function removeExpanded(){
$('#expandSearch').css('display', 'none');
$('#easySearch').css('display', 'block');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="easySearch">
easySearch
<p onclick="showExpanded">Show expanded</p>
</div>
<div id="expandSearch">
expandSearch
<p onclick="removeExpanded">Remove expanded</p>
</div>
The error is due to the fact that you're missing the ()
after the function names in the onclick
attributes, for example:
<p onclick="removeExpanded()">Remove expanded</p>
The functions will also need to be declared in the scope of the window
, so you'll need to move them outside the document.ready event handler.
However, you shouldn't be using the outdated on*
event attributes at all. You should be using unobtrusive event handlers instead. As you're using jQuery already, you can do this:
$(document).ready(function(){
$('.show-expanded').click(function() {
$('#expandSearch').show()
$('#easySearch').hide();
});
$('.remove-expanded').click(function() {
$('#expandSearch').hide()
$('#easySearch').show();
});
});
#expandSearch { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="easySearch">
easySearch
<p class="show-expanded">Show expanded</p>
</div>
<div id="expandSearch">
expandSearch
<p class="remove-expanded">Remove expanded</p>
</div>
Also note the use of CSS to hide the #expandSearch
element on load. This is executed before JS runs, so it will avoid any FOUC.