Link to home
Start Free TrialLog in
Avatar of sabecs
sabecs

asked on

jQuery when a text link is clicked?

I have added jQuery to my page and tested with a plain hello which works fine on page load.

(function($){
         alert('hello');
})(jQuery)


But how would I get it to work when a link is clicked?

<a class="contact-staff-btn"  href="/user/Jane/" target="_blank">Contact Jane</a>

<a class="contact-staff-btn"  href="/user/Pete/" target="_blank">Contact Pete</a>


(function($){

$('.contact-staff-btn').click(function() {
         alert('hello');

      });

})(jQuery)
Avatar of Rob
Rob
Flag of Australia image

The code you've posted is correct though I gather you've posted this question because the page takes you to the link you've clicked on.  If you want to stay on the page you need to tell the browser to ignore the link's event.  Exactly as you see here on the jQuery docs: https://api.jquery.com/event.preventdefault/

Every event in jQuery has the event object passed automatically.  You use that to control, interrogate or cancel the event.

(function($){

$('.contact-staff-btn').click(function(event) {
         event.preventDefault();
         alert('hello');

      });

})(jQuery)

Open in new window

Avatar of sabecs
sabecs

ASKER

Thanks Rod, I tried your code but still no luck?
Then it will be the placement of your javascript as here is an exact working demo of my code http://jsbin.com/betoteq/edit?html,output

make sure you reference the jquery library in the <head> and put your code in a script tag just before the end body tag </body>
Please explain your objective. You have two links, both of which take you to a different page (/user/Jane and /user/Pete) in a new window or tab (target="_blank"). You have jQuery code which opens an alert in the original window (alert("Hello");). These two activities compete with each other. Which do you want to do, open a different page in a new window or open an alert in the original window? And which of these two different actions is not working?
Avatar of sabecs

ASKER

Thanks for your feedback, very much appreciated.

I am basically want to display 3 options to a user when they click on a link, the url will be different based on the user.
I am just using the alert("Hello"); to work out why it is not working.
The code is going into a Wordpress site, could this be an issue?

This works
(function($){
          alert('hello');
 })(jQuery)

But this doesn't
(function($){
$('.contact-staff-btn').click(function(event) {
         event.preventDefault();
         alert('hello');
      });
})(jQuery)




$(function() {
    $('.ab-btn').click(function(e) {
        e.preventDefault();
        var dialog = $('<p>Are you sure you want to cancel?<br/>If you are cancelling within 24 hours please contact professional to advise them of cancellation</p>').dialog({
            buttons: {
                "Yes, Cancel Appointment": function() {alert('you chose yes');},
                "Contact Professional":  function() {
                window.open('url', 'window name', 'window settings');
  							return false;
								},
                "No, Don't Cancel":  function() {
                    dialog.dialog('close');
                }
            }
        });
      });
});

Open in new window

I'm not sure that the following works for you, more importantly the jquery library hasn't initialized:

What does this give you? [object] or null?

(function($){
          alert($);
 })(jQuery)

Open in new window


what you should change it to is to use the jquery init/ready function

jQuery(function($) {
    alert($);
    $('.contact-staff-btn').click(function(event) {
         event.preventDefault();
         alert('hello');
      });
});

Open in new window

Use bind() method:
$('.contact-staff-btn').bind('click',function(e){
     e.preventDefault();
    alert('Hello');
    });

Open in new window

@Leonidas, bind() has been deprecated.  

If the elements do not exist when the page loads, i.e. you're adding the links via JavaScript then you'll need to attach the click handler to an element that does exist when the page loads.

for example:

$('body').on('click','.contact-staff-btn',function(event) {
         event.preventDefault();
         alert('hello');
      });

Open in new window


As the <body> tag should always exist, that will match any descendant element of the body tag with the contact-staff-btn class.
@Rob
Even with this case?:
$(document).ready(function(){
$('.contact-staff-btn').bind('click',function(e){
     e.preventDefault();
    alert('Hello');
    });
});

Open in new window

Avatar of sabecs

ASKER

Thanks for your comments and help, very much appreciated.

(function($){
          alert($);
 })(jQuery)

returns null.
As I suspected that would indicate that the jQuery hasn't loaded.

This appears to work because it's still a function (closure) and it still executes.  You're just passing a null object :)  In the code below you'll get "null" then "hello" popup.

(function($){
          alert($);
          alert('hello);
 })(jQuery)

Open in new window


So where are you including the jQuery library?


@Leonidas - even with that, the .bind() syntax is being dropped.  It will and should work as you've got it for versions pre 3.0
Avatar of sabecs

ASKER

Hi Rob, I have tried to include it using WordPress jQuery plugins but not much luck.
I have found another file that actually gets loaded into the page I am working on called "customer_profile.js"

How would I add my stuff to this file, the alert works on load but I can't workout how to add my code?

(function($) {
    window.booklyCustomerProfile = function(options) {
       $('.ab--show-past').on('click', function(e) {
           e.preventDefault();
           var $self = $(this),
               $table = $self.prevAll('table.ab-appointments-table'),
               ladda = Ladda.create(this);
           ladda.start();
           $.get(options.ajaxurl, {action: 'ab_get_past_appointments', columns: $table.data('columns'), custom_fields: $table.data('custom_fields'), page: $table.data('page') + 1 }, function () {
           }, 'json').done(function (resp) {
               ladda.stop();
               if (resp.data.more) {
                   $self.find('span.ab_label').html(BooklyL10n.show_more);
               } else {
                   $self.remove();
               }
               if (resp.data.html) {
                   $table.find('tr.bookly--no-appointments').remove();
                   $(resp.data.html).hide().appendTo($table).show('slow');
                   $table.data('page', $table.data('page') + 1 );
               }
           });
       });
    };
	
	
	//alert('hello');

	
})(jQuery);

Open in new window

Even that code assumes that jQuery has loaded.

What i'd like you to try is to use the jQuery init function and let me know if this gives you "function() {.....}" in the alert or if it gives you null:

jQuery(function( $ ) {
    alert($);
});

Open in new window

Avatar of sabecs

ASKER

Thanks Rob, I receive the following results.

function (a,b){return new n.fn.init(a,b)}

Where should I place my function, inside or outside the existing (function($) { tags?

(function($) {
    window.booklyCustomerProfile = function(options) {
       $('.ab--show-past').on('click', function(e) {
           e.preventDefault();
           var $self = $(this),
               $table = $self.prevAll('table.ab-appointments-table'),
               ladda = Ladda.create(this);
           ladda.start();
           $.get(options.ajaxurl, {action: 'ab_get_past_appointments', columns: $table.data('columns'), custom_fields: $table.data('custom_fields'), page: $table.data('page') + 1 }, function () {
           }, 'json').done(function (resp) {
               ladda.stop();
               if (resp.data.more) {
                   $self.find('span.ab_label').html(BooklyL10n.show_more);
               } else {
                   $self.remove();
               }
               if (resp.data.html) {
                   $table.find('tr.bookly--no-appointments').remove();
                   $(resp.data.html).hide().appendTo($table).show('slow');
                   $table.data('page', $table.data('page') + 1 );
               }
           });
       });
    };
	
	

    jQuery(function( $ ) {
    alert($);
    });


	
})(jQuery);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sabecs

ASKER

Thanks for your help, very much appreciated.