Remove 'onclick' command from a child of a div - javascript

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.
}
};

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.

Getting the current div id in content-editable div(specific)

I am recently working on one of my projects and currently i am stuck in some problem. Well, i have made a content editable div where the user can type its input. This content_editable div contains several div's in which user has to type. I tried document.activeElement but it gives me the content_editable div not the specific div and that the one with id second_div
I want to know how to find that specific div in content_editable div where user is type.For example:-
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
I am the first div
</div>
<div id="second_div">
I am the second div and i want to know if the focus is on me
</div>
</div>
My Javascript:
window.onload = function () {
getDivwhohasfocusincontentedtiablediv(); // Something like that
};
I can use jquery but only at the last choice. I want to use only javascript for this purpose.Please help me to solve this, i didn't find solution for this all the net ( it could be that i haven't searched carefully). Thanks in advance
One possible solution is to attach an Event Listener on each inner div to listen for "focus" event. However I found out that not all elements emit "focus" events.
JQuery docs says:
The focus event is sent to an element when it gains focus. This event
is implicitly applicable to a limited set of elements, such as form
elements (input, select, etc.) and links (a href). In recent
browser versions, the event can be extended to include all element
types by explicitly setting the element's tabindex property. An
element can gain focus via keyboard commands, such as the Tab key, or
by mouse clicks on the element.
Adding tabindex attribute to each inner div will make it possible to listen to focus events.
Example at JSFiddle. Note: I wrote the code in JQuery but it can easily be written in JS.
You can find focus element in js using this,
var focused = document.activeElement;
What about this ,
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
First Div
</div>
<div id="second_div">
Second Div
</div>
</div>
$(document).ready(function () {
function onMouseUp(e) {
console.log(this.id);
}
document.getElementById("first_div").addEventListener("mouseup", onMouseUp, false);
document.getElementById("second_div").addEventListener("mouseup", onMouseUp, false);
});
Demo Here JS FIDDLE
to get specific div
in Javascript you can use
document.getElementById("second_div")
or using Jquery
$("#second_div")
make sure your id was unique. This is the fastest way to find obj in any browser.
now for getting getting the active div. why not put specific event whenever the div was clicked or edited. like:
$("#second_div").click (function (){
//raise flag or something
currentDiv = "second_div";
})
function getCurrentDiv()
{
//do something in currentDiv
}
or try also explore other event such as, on mouse over, on mouse leave, etc.
i hope that might help. other wise, please elaborate your question if I missed something.

page scrolls down when clicking href=#SomeDivName

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.

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.

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Categories