1

In certain conditions I want to open links in the same window, while in others I want to open them in a new window. I have the following jQuery code:

if (internal) {
    jQuery(".main a").removeAttr('target');
} else {
    jQuery(".main a").attr('target', '_blank');
}

I have two <a>s contained in the "main" div. One is directly under the div while the other is buried under a couple of sub-divs. When it runs, it only adds the blank target to the first <a> tag. However, when I set a breakpoint through Firebug and step through it, everything works fine. Is there a reason it wouldn't work at full speed? What's the workaround?

3
  • 1
    Find the smallest HTML sample where you can reproduce this and post it here. Problem sounds a little strange and shouldn't happen really. Is the HTML valid? Commented Nov 29, 2009 at 20:19
  • 1
    i agree, it might be bad HTML syntax Commented Nov 29, 2009 at 20:25
  • No, the HTML checks out as valid. Also, there's no easy to simplify the control into something postable. I'll think about that though. Commented Nov 30, 2009 at 2:43

2 Answers 2

1

Is the particular code executed during the onload event? In jQuery you normally use $(document).ready() for this. E.g.

$(document).ready(function() {
    // Do stuff onload.
});

Otherwise it would be executed immediately while the HTML DOM tree is still not fully built up and initialized yet.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 For an excellent reasoning. I agree that this sounds like this is the problem.
Excellent theory, but no. The function is run as the result of a click on the page. You click on a thumbnail image, and the "main" area displays a large image. Clicking on the image sends you to an external site or another internal page. However, there's also a button that has the same link. That's the one that doesn't work.
OK, got it. There was actually an animate to put the button into place, and at full speed it wasn't done by the time the attr function ran. The breakpoint changed the timing so everything worked. This answer is close enough that I'm going to call it right.
0

Try using each() to step through the A elements:

jQuery(".main a").each(function() {
  $(this).attr('target', '_blank');
});

2 Comments

He shouldn't have to do that. Setting attributes effects all selected elements: docs.jquery.com/Attributes/attr#keyvalue
I was sure this was going to work, but it has the same behavior. It doesn't work under normal conditions, but when I put in a breakpoint, then everything is fine.

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.