0

I'm trying to give the same function to 2 elements.

Here's what I've got which isn't working:

$(document).ready(function() {
   $('#menu a, p.bodytext a').click(function() {
      $('#content_bg').load($(this).attr('href')+' #content');
      return false;
   });
 });

Now it works if I go like this:

$(document).ready(function() {
   $('#menu a').click(function() {
      $('#content_bg').load($(this).attr('href')+' #content');
      return false;
   });
 });

or like this:

$(document).ready(function() {
   $('p.bodytext a').click(function() {
      $('#content_bg').load($(this).attr('href')+' #content');
      return false;
   });
 });

But does not work with them together.

Suggestions?

7
  • That seems unlikely; are you sure the selectors are correct? That you've not missed out a comma, or misspelled something? Commented Mar 5, 2012 at 21:42
  • Works fine for me. jsfiddle.net/C2e9r Commented Mar 5, 2012 at 21:42
  • What is not working? Can you describe the error? Commented Mar 5, 2012 at 21:42
  • In the code I'm using now, the #menu a is working, but the p.bodytext a is not. When a link is clicked from the bodytext paragraph, it refreshes the page and loads the content, whereas the #menu a link opens the link within the frame it's supposed to go on the page, without refreshing the page. Commented Mar 5, 2012 at 21:51
  • Can you reproduce your problem with JS Fiddle, perhaps, so you can let us see what you're working with? Commented Mar 5, 2012 at 22:04

4 Answers 4

1

Use the add method to add elements to a set:

$('#menu a').add('p.bodytext a').on();
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$(function() {
   $('#menu, p.bodytext').find('a').on('click', function() {
      $('#content').load($(this).attr('href')+' #content');
      return false;
   });
 });

Comments

0

Use class name instead of id.

$(document).ready(function() {
   $('.myClass').click(function() {
      $('#content').load($(this).attr('href')+' #content');
      return false;
   });
 });

1 Comment

#menu a works, it's the p.bodytext a that doesn't with the code I'm using.
0

I suggest to add a receive the parameter 'e' and do a e.preventDefault().

like this

$(document).ready(function() {
  $('#menu a, p.bodytext a').click(function(e) {
     e.preventDefault();
     $('#content').load($(this).attr('href')+' #content');
     return false;
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.