Reputation: 1434
I need some buttons which on click shows the related div
s and hide the rest.
I googled the below code. It is working as expected on jsfiddle.net, but it's not on my server. I get something like this, and of course the 'buttons' aren't working as well:
button1 button2 button3 button4 button5
part1
part2
part3
part4
part5
Code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.showSingle').on('click', function () {
$(this).addClass('selected').siblings().removeClass('selected');
$('.targetDiv').hide();
$('#div' + $(this).data('target')).show();
});
$('.showSingle').first().click();
</script>
<div class="buttons">
<a class="showSingle" data-target="1">button1</a>
<a class="showSingle" data-target="2">button2</a>
<a class="showSingle" data-target="3">button3</a>
<a class="showSingle" data-target="4">button4</a>
<a class="showSingle" data-target="5">button5</a>
</div>
<div id="div1" class="targetDiv">part1</div>
<div id="div2" class="targetDiv">part2</div>
<div id="div3" class="targetDiv">part3</div>
<div id="div4" class="targetDiv">part4</div>
<div id="div5" class="targetDiv">part5</div>
Upvotes: 0
Views: 153
Reputation: 96
If you are using the script in your local system, add the "https:" or "http:" protocol in the external script URL.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your jQuery methods inside a document ready event:
<script type="text/javascript">
$(document).ready(function(e) {
$('.showSingle').on('click', function () {
$(this).addClass('selected').siblings().removeClass('selected');
$('.targetDiv').hide();
$('#div' + $(this).data('target')).show();
});
$('.showSingle').first().click();
});
</script>
Upvotes: 0
Reputation: 4636
Use the following at the beginning of your script:
$(document).ready(function(){
//Your logic
});
Upvotes: 2
Reputation: 11865
you need to place your jquery code inside a document ready block. this would look like this
<script type="text/javascript">
$(document).ready(function(){
$('.showSingle').on('click', function () {
$(this).addClass('selected').siblings().removeClass('selected');
$('.targetDiv').hide();
$('#div' + $(this).data('target')).show();
});
$('.showSingle').first().click();
});
</script>
This block basically tells jquery to only execute the encompassed code once the DOM has been loaded, this is required as your code is manipulating DOM element.
Upvotes: 1
Reputation: 207901
You need either place your jQuery at the end of the page, or wrap it in a document.ready call (e.g. $( document ).ready(function() {...
).
You're attempting to execute code on elements that don't yet exist. jsFiddle defaults to a window.onload which is why it works there.
Upvotes: 1