page scrolls down when clicking href=#SomeDivName - javascript

I'm using Twitter's Bootstrap topbar.
When I click on some navigation href
href=#SomeDivName
Like when you press the navigation in this page:
http://twitter.github.com/bootstrap/examples/fluid.html#contact
The page scrolls down a bit.
I want the relevant section will appear after clicking,
but I don't want the page to scroll down.

$('a[href="#SomeDiveName"]').on('click', false);
This will return false when you click on the anchor tag with an href attribute set to #SomeDiveName. Which will prevent the default behavior of the element, which in this case is to scroll to the element to which the href attribute refers.
If you have a set of these links then I'd suggest adding a class to identify them so you can select them all at once:
$('.stop-this-link').on('click', false);
This will prevent the default behavior for all elements with the stop-this-link class whenever the element is clicked. Selecting by class is a lot faster than by attribute too. When searching by attribute, every element in the DOM must be checked.
Note that returning false in a jQuery event handler is the same as calling: event.preventDefault() and event.stopPropagation().
For more info about these functions see here:
event.preventDefault(): http://api.jquery.com/event.preventdefault
event.stopPropagation(): http://api.jquery.com/event.stoppropagation

instead of using <a href="#target"> use <a data-target="#target"> and remove the href attribute

Jasper's answer is correct, however you might get some weirdness if you bind other things later. I tend to use this:
$('.stop-this-link').on('click', function(e){ e.preventDefault() });
Essentially the same thing, but importantly it does not stop propagation of the event up the DOM, at the cost of being slightly more verbose.

Related

Google Tag Manager click event not bubbling up to parent

I'm setting up Google Tag Manager on a client's site and I'm having trouble getting click event tags to fire.
I have the trigger set to fire on the button's CSS selector.
The button itself has some child elements, including an svg icon. When the svg is clicked, the click is registered in the data layer, but the tag is not fired. The tag only fires when I select the button itself.
I also tried removing event listeners in my own scripts that were attached to these buttons in case a return false; or e.stopPropagation() was blocking it, but this didn't change anything.
I had the understanding that GTM listens for click events that bubble up to the document. If this is the case my tag should fire when a child is clicked, right? Or am I misunderstanding something?
Alternatively, should I push the event to the dataLayer in my scripts rather than using a click trigger?
screenshots
10 gtm.click correctly fired the tag
9 gtm.click was the child svg that did not
The last screenshot is the firing rule for my trigger.
I've encountered this type of problem a lot. It happens with <i> tags for things like glyphicons as well. Simply add CSS pointer-events:none; to that SVG (unless you require that SVG to be clickable and not just the parentElement). The pointer-events:none on the SVG will mean that when it is clicked the click event registers on the parent element.
Best way would be to have the client developers add the JS. the more hacky way would be to run something like this in a custom HTML tag via GTM
jQuery('a.link-youre-tracking svg').css('pointer-events','none)
Grate solution/idea to use:
pointer-events:none
But what happens when you have complex div (20 classes and 15 elements inside) and you wrap this div with a link <a> tag (For blog postcard for example).
For now GTM lack of a normal solution for this issue :( For complex structure you should add "extra div" for pointer-events (Work fine but "not elegant").
<a class="track-this-click-by-gtm" href="url">
<div style="pointer-events:none">
extra unwanted div
<i></i>
<p>hello</p>
<ul><li>hello2</li></ul>
<date>2019</date>
lorem
</div>
</a>
As said before the “Just Links” trigger will bubble to the parent <a>, so using that instead of “All Elements” should solve any issues you have with clicks registering on children of an <a>. But what if you’re trying to register clicks on a parent <button>, for example? Then you could use a Custom JavaScript variable called “Find closest” with this function:
function () {
return function (target, selector) {
while (!target.matches(selector) && !target.matches('body')) {
target = target.parentElement;
}
return target.matches(selector) ? target : undefined;
}
}
And then use that function in another Custom JavaScript variable like this:
var elementFound = {{Find closest}}({{Click Element}}, 'button');
Read Simo Ahava’s article on this for more info.

How can I exclude this element from an inherited link?

I have a site at whensayfeed.meteor.com. Each of those "Posts" is a nested in a <a></a> element. The heart on the right side of each one is supposed to be a "like button" so it also needs to be clickable. However, since it's nested in an <a> it just goes to that address when clicked. I need a way to either exclude this element, or do this in some other way. I've tried to just nest the .chant element in the link, but it doesn't pick up that click. What do you believe I should do?
Nesting tags is illegal
Try making your like button a link that's outside of the post link. You can then use position: absolute to overlap your like button on top of the post.
Try this:
Set the z-index: 0; of .post-contain instead of previous z-index: -20;.
Have a function receiving anchor click events like so:
function onAnchorClicked(e){
if(e.target.nodeName==='IMG'){
console.log('Image clicked');
e.preventDefault();
}else{
console.log('Anchor clicked');
}
}
Assign the click event to all anchor tags: $('a').on('click',onAnchorClicked);
This way, you can do what you want to do when img is clicked.
Having said that, although HTML5 does allow block-level elements to be nested inside an anchor tag but legacy browsers will have a hard time.
A solution to that perhaps could be to have your posts wrapped around a div element instead of anchor which behaves like an anchor tag accompanied by a data-link attribute with values containing your links that you can populate from backend e.g.:
<div class="anchor-link" data-link="LINK GOES HERE">...</div> and then assign the click as described above (changing the selector obviously).
Hope this helps.

What is the right href value for a JavaScript anchor tag?

I usually have to bind a JavaScript function to an anchor-click event. That is easy using jquery or the onclick inline attribute.
But, my problem is that I never know what the best way to keep href empty is.
For instance:
<a href="javascript:void(0)"> - It seems like a bit too much code for just being empty
<a href=#> - If I don't want to move to another page, I must return
false in the JavaScript call
<a href> - This option breaks the
cursor and hover style and the browser doesn't render it as a link
<a> - idem
What is the best href value for empty anchors? I'm not interested to keep functionality without JavaScript
The right one is to use an empty a element href attribute and bind the click event in Javascript.
For unobtrusive design, you should have a href attribute with a proper link (so those without Javascript can still use the site) and remove the attribute in Javascript, binding the click event.
If you are simply using the a element as a target to bind the click event to, consider using a div or span instead.
I'm personally a firm believe in using JavaScript to extend functionality, not replace. With that said, I leave anchors pointing to a "safe" fall-back of the action I'm really just executing with javascript. Simply put:
Then, supplement (and return false) if javascript was able to successfully load and bind to the element, otherwise still provide the user the ability to accomplish the task if they don't have javascript (either blocked via plugin or just not loaded).
Simply do not use A element. You can as well make DIV clickable or any other element.
Or you can also simply leave href attribute out, like so.
<a onclick="myFunction();">dasd</a>
If you also want to look it like a link, put this in CSS:
a {
text-decoration: underline;
color: blue;
}​
I think
or
is the best way to indicate empty anchor.
and
will move the page to the dom element which has id="someId"
it all depends. if you are clicking an anchor to open a panel on the page then I am happy to use option 2 but only if I insert that anchor with javascript.
this then means with javascript disabled the anchor doesn't show and the panel should be visible.
if the link goes somewhere then you need the actual link address like brad christy and odid said.
<a href=#>ABC</a>
=> on click of above link it will set url in address bar which makes flickering of document or resetting scroll position
to avoid above problem,
<a href=# onclick="return false" >abc</a>
can be used and bind event handler using jQuery as usual
or you can execute any function on onclick which return false value.

removeAttr("href") on anchor also removed text color

I have a web site that uses JQuery and JQuery UI.
For some links, I didn't want to use JQuery UI Theme's colors, so I overrided using my own css.
It all worked until I used $("#a_about").removeAttr("href") to remove the href from the anchors (so that the link wouldn't actually work, I just want to grab the click action)
to my surprise, it also removed the color which my css applied, and returned to the color which JQuery UI Theme applied previously.
I tried to change the element on which the color is applied (the anchor itself, the parent container, etc...) but nothing helped.
Thanks...
Instead of:
$("#a_about").removeAttr("href")
Use:
$("#a_about").attr("href","javascript:;")
It's because on some browser, a anchor a without attribute href is treat as normal text. So try change the href to javascript:; instead of remove it.
Anchor without href is not really a link. As others said set it to something like # and to "cancel" the click, also have:
$("#a_about").attr("href", "#").click(function() { return false; });
Don't touch the href. Prevent the default action in the event handler instead.
This way the link will continue to work if people, for example, middle click on it.

Remove 'onclick' command from a child of a div

I am working on a website where I have a main div. I wanted all of the div's page-area to act as a link (clicking on it will cause a submitting of a form and moving to another page) so I added to that div the attribute:
<div class="box1" onclick="javascript:document.forms['womenForm'].submit();" ...>
Everything in this area shuold link to the next page apart from an HTML selection that is inside this div, but should be clickable without moving to the next page.
How can I cause this to happen? I tried to wrap the selected element with a div, giving it href="" or onclick="" but still the form is submitted.
Can anybody resolve this?
You need to stop the bubbling of the event up the hierarchy ...
using the onclick attribute you can do this with
onclick="event.cancelBubble=true;if(event.stopPropagation) event.stopPropagation();return false;" on the select element.
First, the javascript: pseudo-protocol is superfluous in your code because you're using the "onclick" attribute.
I suggest moving away from inline JavaScript and venturing into the more acceptable unobtrusive JavaScript world.
Anyway, what you want to do is check that the event was not fired on a <select> element. With unobtrusive JS that would go something like this:
someElement.onclick = function(e) {
var target = e ? e.target : event.srcElement;
if (!/option|select/i.test(target.nodeName)) {
// do stuff.
}
};

Categories