Combining document ready scripts? - javascript

I'm using a simple show-hide script on various IDs. The issue is as it stands right now each is a seperate JS that calls the document ready function via jQuery.
Is there a way to combine this into one more flexible script or at least into one script in some form or another. Thank you so much for your time in advance!
Below is an example:
<script type="text/javascript">
$(document).ready(function () {
$("#loadDummy7").hover(
function () {
$("#dummy7").show();
}, function () {
$("#dummy7").hide();
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#loadDummy8").hover(
function () {
$("#dummy8").show();
}, function () {
$("#dummy8").hide();
});
});
</script>

You can combine it into a single script like this:
$(function(){
$("[id^='loadDummy']").hover(function() {
$("#" + this.id.replace('loadD', 'd')).toggle();
});
});
This uses the attribute-starts-with selector to get all id="loadDummyXXX" controls and finds the element to toggle with the corresponding dummyXXX ID. An easier way would be to use classes and find it relatively, for example if your markup was like this:
<div class="dummyWrapper">
Stuff
<div class="dummy" style="display: none;"> More Stuff</div>
</div>
You could do it like this, much cleaner:
$(function(){
$(".dummyWrapper").hover(function() {
$(this).find(".dummy").toggle();
});
});

Related

Is there any way to shortcut this method? Hide/Show element on jquery

I would like to ask you guys if I can shortcut this code as I think it can be more less code but I'm learning right now Javascript/Jquery.
Thanks!
<script type="text/javascript">
$(document).ready(
function(){
$(".facebook").click(function () {
$("#facebook_prices").show("slow")
$("#twitter_prices").hide("slow")
$("#youtube_prices").hide("slow");
});});
$(document).ready(
function(){
$(".twitter").click(function () {
$("#twitter_prices").show("slow")
$("#facebook_prices").hide("slow")
$("#youtube_prices").hide("slow");
});});
$(document).ready(
function(){
$(".youtube").click(function () {
$("#youtube_prices").show("slow")
$("#facebook_prices").hide("slow")
$("#twitter_prices").hide("slow");
});});
</script>
The first thing to do is to only use one document.ready handler. You don't need to repeat it for every operation.
The pattern you're looking to follow here is called 'Don't Repeat Yourself', or DRY. To achieve this you can apply common classes to the elements which trigger events and use the href (assuming the trigger is an a element) or data attributes to store custom metadata to separate the actions performed by each element. Try this:
$(document).ready(function() {
$(".trigger").click(function(e) {
e.preventDefault();
$('.price').hide('slow');
$($(this).attr('href')).show("slow")
});
});
.price {display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Facebook
Twitter
Youtube
<div class="price" id="facebook_prices">
Facebook prices...
</div>
<div class="price" id="twitter_prices">
Twitter prices...
</div>
<div class="price" id="youtube_prices">
Youtube prices...
</div>
You can use comma ( , ) to similar elements to hide()
Check below code :
$(document).ready(function () {
$(".facebook").click(function () {
$("#facebook_prices").show("slow");
$("#twitter_prices,#youtube_prices").hide("slow");
});
$(".twitter").click(function () {
$("#twitter_prices").show("slow");
$("#facebook_prices,#youtube_prices").hide("slow");
});
$(".youtube").click(function () {
$("#youtube_prices").show("slow");
$("#facebook_prices,#twitter_prices").hide("slow");
});
});
Check the below implementation. Removed the repetitive .ready() methods and merged the hide functions.
<script type="text/javascript">
function hideAll(){
$("#facebook_prices").hide("slow")
$("#twitter_prices").hide("slow")
$("#youtube_prices").hide("slow");
}
$(document).ready(
function(){
$(".facebook").click(function () {
hideAll();
$("#facebook_prices").show("slow");
});
$(".twitter").click(function () {
hideAll();
$("#twitter_prices").show("slow");
});
$(".youtube").click(function () {
hideAll();
$("#youtube_prices").show("slow");
});
});
</script>
Hope this helps :)

How to call a function when a div is dynamically generated using jQuery

The scenario I want to achieve is as follow:
$("#parentDiv").on("load",'#childDiv', function () {
// do something...
});
I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.
Instead of load, you can make use of a custom event which gets triggered with .trigger():
$(document).ready(function() {
$("button").on("click", function() {
$("body").append("<div id='new'>Created</div>").trigger('custom-event');
});
});
$(document).on("custom-event", function() {
console.log('DIV created!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Create element</button>
</body>

jQuery getting data attribute not working

I have a script that produces a number of buttons with a class and I want it to alert the data attribute on click but it's not working.
Here is the output of HTML
<button class="request box-button" data-value="18492500814">Request</button>
jQuery code
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).data('value'));
});
});
});
Since your elements don't exist when the page loads, the event won't be bound to them. Fix that by using event delegation:
$(document).ready(function(){
$(document).on('click','.request', function () {
alert($(this).data('value'));
});
});
JS Fiddle demo with dynamically generated elements
Note: Here, I used $(document).on() because I don't have your page's structure. But if you insert the buttons in a container that already exists in your HTML, use this instead: $('#myContainer').on(). It won't be noticeable, but it is best for performance.
Why not just have the listener on request, instead of inside of the loop. Also use the attr to get the data-value
$(document).ready(function(){
$('.request').click(function () {
alert($(this).attr('data-value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>
Try with attr method.
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).attr('data-value'));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>

jQuery show / hide not working

Tried to look at all the other questions about why this isn't working, no luck. I'm loading this in my header:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
Here is my script:
$(document).ready(function() {
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});
$(function () {
$("#patient-portal-link").click (function (event) {
$("#patient-portal-tab").show();
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});
});
$(function () {
$("#knee-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").show();
$("#shoulder-tab").hide();
});
});
$(function () {
$("#shoulder-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").hide();
$("#shoulder-tab").show();
});
});
Here are the links that are meant to call up the script:
<ul>
<li><a id="#patient-portal-link">Patient Portal</a></li>
<li><a id="#knee-link">Knee</a></li>
<li><a id="#shoulder-link">Shoulder</a></li>
</ul>
And then I have the three divs which are named as follows:
<div id="patient-portal-tab">Patient portal content</div>
<div id="knee-tab">Knee content</div>
<div id="shoulder-tab">Shoulder content</div>
The knee and shoulder divs hide correctly on page load, but the links do nothing. I'm using Google Chrome and when inspecting element, I get no errors reported for javascript. What am I doing wrong?
Remove the # characters from your ID values. The # character in jQuery denotes an ID of an element, so you would need two #'s (##knee-tab) for this to work.
Are you sure you have the # symbol infront of the Ids. ReWrite it like this and it will work
<li><a id="patient-portal-link">Patient Portal</a></li>
<li><a id="knee-link">Knee</a></li>
<li><a id="shoulder-link">Shoulder</a></li>
your problem is in your HTML code. The id's in HTML doesn't need the hash '#'.
$(function() ... ) is just shorthand for $(document).ready(function() ...) if i recall correctly. So you are using too many ready calls. Try this:
$(document).ready(function() {
$("#knee-tab").hide();
$("#shoulder-tab").hide();
$("#patient-portal-link").click (function (event) {
$("#patient-portal-tab").show();
$("#knee-tab").hide();
$("#shoulder-tab").hide();
});{
$("#knee-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").show();
$("#shoulder-tab").hide();
});
$("#shoulder-link").click (function (event) {
$("#patient-portal-tab").hide();
$("#knee-tab").hide();
$("#shoulder-tab").show();
});
});
Click here
check this fiddle
in this code you have entered extra # to the id
overwrite your previous html to the html code given in fiddle

JQuery with Element ID

I am trying to create a bit of jquery code to update an element but im having a problem. It wont update and I think its because of the element id?
Here is my JS Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#vote_button_" + $(this).attr('id')).click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
And this is the HTML Code:
<div class="vote_container">
<div class="vote_button" id="vote_button_31"><img src="/images/picture_31.png"></div>
<div class="vote_count" id="vote_count">0</div>
</div>
You're telling it to use the ID of the document (I think).
You can surely just do:
$("#vote_button_31").click(function()
{
$("#vote_count").show().html('<h2>voting, please wait...</h2>');
});
If you want the code to work on all vote buttons try this:
$(".vote_button").click(function()
{
$(this).siblings('.vote_count').show().html('<h2>voting, please wait...</h2>');
});
$("#vote_button_" + $(this).attr('id')).click(function()...
The way you've called it, this has no context at all. Since you have a class on the div in question, why not use that instead?
$(".vote_button").click(function() {...
That will also work if you don't know the id in question when the page is loaded. If you're dynamically adding the divs then you might want to use live or delegate:
$(".vote_button").live("click", function() {...
Why you don't select the element directly:
<script type="text/javascript">
$(document).ready(function()
{
$("div#vote_button_31").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
YOu cannot do this. Instead try this:
<script type="text/javascript">
$(document).ready(function()
{
$(".vote_button").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});

Categories