Javascript - Stop scrolling on certain links - javascript

For example,
Foo
Bar
...
<div id="foo"></div>
<div id="bar"></div>
Is there a way to selectively stop scrolling for certain elements?
In the example, above, what if I want the browser to not scroll to the #bar element if the anchor that has `href="#bar" is clicked?
Is this possible?

Use a click handler that returns false, which prevents the default click action.
Bar

yes, what you are looking for is how to prevent browser default behaviour
example (using jQuery)
$('a').on('click', function(event){
if($(this).attr('href') == '#bar'){
event.preventDefault();
}
});

Well, one of thr ways that I can suggest is to remove the href attribute in some specific circumstances. But removing href attribute may result in the anchor appear to be not clickable anymore...
If you want your anchor to still appear to be clickable:
'$("a").removeAttr("href").css("cursor","pointer");'
You may specify ids for specific anchor elements.

If you add a class or id to links that you don't want to scroll, you can then add an event listener to those links and prevent the default action on click.
HTML
Foo
Bar
...
<h2 id="foo">Foo</h2>
<h2 id="bar">Bar</h2>
Javascript
var blockedLinks = document.getElementsByClassName('blockedLink');
for (var i = 0; i < blockedLinks.length; i++) {
blockedLinks[i].addEventListener('click', function (e) {
e.preventDefault();
}, false);
}
Demo

Related

How to change image when two buttons are clicked?

I want to make jQuery script where I will have 10 buttons all with different colors and after user clicks on two different buttons, combination of the clicked buttons colors will be made and switch the image frame with already prepared images based on color combinations.
My question is how to put conditions for two buttons(or links) clicked.
switch me
<img src="http://placehold.it/333/fe3/img/picture2.jpg" id="bg" />
$(function() {
$('.menulink').click(function(e){
e.preventDefault();
$("#bg").attr('src',"http://placehold.it/333/3ef/img/picture1.jpg");
});
});
I want to achieve something like this but I want image to change when two buttons (or links) are clicked.
http://jsfiddle.net/maniator/Sevdm/
provided you wanted to make sure the buttons were unique when clicked, you'll want a way of tracking which have been seen. I'm using a JS Object like a Set here for compat with older browsers.
var clickCount = 0;//count the clicks
var clickTracker = {};//track which id's were clicked
var clickThreshold = 2;//the number of clicks we want before executing the if block
function clickHandler(){//callback function for the event
if(clickTracker[this.id] === undefined){//we haven't seen this id yet
clickCount++;//increment the number of buttons clicked
clickTracker[this.id] = 1;//flag for tracking the click
if(clickCount >= clickThreshold){//we saw at least clickThreshold clicks
console.log(clickCount + 'unique clicks happened!');
//your work here
}
}
}
$('.cls').click(clickHandler);//bind events
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn1' class='cls'>1</button>
<button id='btn2' class='cls'>2</button>
<button id='btn3' class='cls'>3</button>
<button id='btn4' class='cls'>4</button>
<button id='btn5' class='cls'>5</button>
You can use event delegation to track clicks on .menulink elements. using e.delegateTarget we can have the parent container hold a variable that determines if a .menulink element has been clicked previously, and if it has, we can have it change the background.
To do this I switched the click method to an on method. The on methods parameters are:
$(element).on(event, delegated selector, function)
JQuery .on documentation
Delegation simply means that instead of checking if each button has been clicked by placing an event on the button, we place an event on the container of the buttons and ask if the element that caused the event matches our delegated selector. If it does the provided function is fired. To access the parent of the delegated element within the code we can use the passed back event object, or in this case e.delegateTarget
JQuery delegateTarget documentation
Since everything in JavaScript is an Object, we can assign new properties and methods to anything that is not explicitly part of the Browser's most base architecture. This absolutely includes the body of a page.
In the code below, I place a new property clicked on the body of the page. This is added on click of the first .menulink element, and is checked upon each subsequent click.
Because of this we can know if it is a second click by determining if body.clicked is true. If it is we tell the script to change the background image.
$(function() {
$('body').on("click", ".menulink", function(e){
if(e.delegateTarget.clicked) $("#bg").attr('src',"http://placehold.it/333/3ef/img/picture1.jpg");
else e.delegateTarget.clicked = true;
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
switch me
switch me
<img src="http://placehold.it/333/fe3/img/picture2.jpg" id="bg" />
This is what I was looking for
<script>
$(document).ready(function() {
var chosenColors = [];
$(".colors button").click(function() {
chosenColors.push($(this).text())
check();
});
function check() {
if (chosenColors.length === 2) {
$(".pretty-picture").attr("src", chosenColors.sort().join("-") + ".png")
chosenColors = [];
}
}
});
</script>
<body>
<div class=colors>
<button type="button">red</button>
<button type="button">yellow</button>
<button type="button">blue</button>
</div>
<img class="pretty-picture">
</body>

href called issue in onclick function [duplicate]

If I have this element:
Item
How can I make both href and onClick work, preferably with onClick running first?
You already have what you need, with a minor syntax change:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)
Use jQuery. You need to capture the click event and then go on to the website.
$("#myHref").on('click', function() {
alert("inside onclick");
window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
To achieve this use following html:
Item
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
No jQuery needed.
Some people say using onclick is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.
We can style a button to look like an anchor element.
From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#onclick_events
Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.
Use ng-click in place of onclick. and its as simple as that:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>

Preventing event bubbling (for javascript onclick events)

I am using javascript to interact with a CMS which provides a button for users to add things to their basket.
However, I am using the javascript to try and prevent the customer from doing so unless they have made a selection from a drop-down menu elsewhere on the page.
As there are many different buttons that could potentially get them to the basket (including the example below) and all of which have different methods for doing so, rather than write many lines of code to prevent each method and then re-enable that method when a selection is made I am trying to do a kind of 'catch-all' fix where I just cover any such buttons / links with another div so as to effectively 'mask' the button below it until they make a decision.
I first tried to use absolute positioned divs to do this which works beautifully until the user does something like re-size a textbox on the page and then suddenly my absolutely positioned div is in the wrong place!!
So I'm now using JQuery's .wrap() which solves this problem nicely.. BUT.. Now I can't use z-index to position the div above the required buttons as those buttons are within the mask not below it!
I have done a lot of reading about event bubbling but I am not sure whether I've not found the right information yet, or maybe I understand it correctly or possibly that event bubbling is leading me down the wrong path all together as I can't seem to take those concepts and apply them to this scenario.
so.....
given the following HTML structure:
<div class="btnMask">
<div class="button">
<a onclick="pageSubmit();return false;" href="#" id="addToBasket">
<span>Add to Basket</span>
</a>
</div>
</div>
where the div with class="btnMask" is added by my javascript.
Plus the following JQuery:
$('.btnMask').click(function() {
// prevent default actions and alert the customer to select something;
});
How do I go about stopping the tag firing when clicking the .btnMask div?
and (in case the answer to that does not make the answer to my other question obvious...)
How would I switch that on and off ? (I have a function that checks the drop-down onchange and sets the z-index to 99 / -99 so I would want to change this to incorporate this new method.)
Thank you in advance for your help.
<< EDIT >>
Using the initial answers to this I managed to solve the problems for links that take you away from the page using a regular href.
So I have now fixed the links where the HTML is like the following:
<div class="btnMask">
<div class="button">
<a id="nextPage" href="/link/toanotherpage.asp?id=667868465726122926234">
<span>Click to go to Page 2</span>
</a>
</div>
</div>
However, like I said there are many methods being used to take people away from the page and and e.preventDefault(); and e.stopPropagation(); don't work for my original example (presumably because they use an onclick rather than a href ?).
Is there a way to do the same thing as e.preventDefault(); and e.stopPropagation(); are doing on my .btnMask div but will also deal with contained links that are being trigged by an onclick?
thanks
<< EDIT >>
Updated the question title to reflect the exact issue rather than just event bubbling on regular links.
If you want to prevent event bubbling and cancel default action then you can return false from the event handler.
$('.btnMask').click(function() {
return false;
});
Or use preventDefault and stopPropagation
$('.btnMask').click(function(e) {
e.preventDefault();
e.stopPropagation();
});
$('.btnMask').click(function(e) {
e.stopPropagation();
});
Your onclick handler is fired before your jquery click handler. You can do something like this
function pageSubmit() {
alert('pageSubmit');
}
var link = document.getElementById('addToBasket');
var linkClickHandler = link.onclick;
link.onclick = null;
$('.button').data('linkClickHandler', linkClickHandler);
$('.button').on('click', function(e){
var clickHandler = $(this).data('linkClickHandler');
var link = $(this).find('a').get(0);
clickHandler.apply(link, [e]);
});
$('.btnMask').on('click', function(e){
if (!$(this).hasClass('test')) {
e.preventDefault();
e.stopPropagation();
}
});
and the html as
<div class="button">
<a onclick="pageSubmit();return false;" href="#" id="addToBasket">
<div class="btnMask test">
<span>Add to Basket</span>
</div>
</a>
</div>
If you remove the class test from btnMask div the pageSubmit handler will not be called,
and when it is present the handler is called.

Allow clicking a link through a div that is bound to the "click" event

I have a div containing some content, in which there are some links. The div itself watches for the click event so it can make the content editable. However, I want the user to be able to click the links inside of the div and have it navigate to the linked page rather than edit the content (clicking anywhere else in the div should edit the content though). How do I achieve this?
Code example:
<div id="content">
Here's a link.
</div>
// jQuery Javascript:
$("#content").click(function() {
// Make content editable
});
(Clicking on the link shouldn't make the content editable, and instead should direct the page to google.com.)
Edit: I'm using my own code to make the content editable (switching out the div with a text area, that sort of thing).
Check the event target and return true
$("#content").click(function(e) {
if ($(e.target).is('a')) {
return true;
}
});
Not tested
The thinking behind this is to bail-out early from the handler and, by returning true, allow the browser to handle the event the usual way.
One error you have is that you are using content as a class in your HTML, but as an ID in your jQuery. So you should change your HTML to id="content" (assuming no other elements on your page already have that id.
Your Javascript can look like:
$("#content").click(function(){
this.setAttribute('contenteditable', 'true');
$(this).focus();
}).blur(function(){
this.setAttribute('contenteditable', 'false');
});
$("#content a").click(function(e){
e.stopPropagation();
});
Here's a JSFiddle: http://jsfiddle.net/q77Bs/
example
use event.stopPropagation()
// jQuery Javascript:
$(".content").click(function(e) {
// make content editable
});
$('.content a').click(function(e) {
e.stopPropagation();
});
You could change the z-index of the link to be greater than that of the div (not sure if that will work), or you can place each link inside another div with a higher zindex than the main div. This will prevent clicks from registering on the primary div, so make sure the secondary divs are correctly sized so as not to prevent the editing functionality
$('#content a ').live("click", function(event){
event.stopPropagation();
});
this will do the trick

how to make the menu close if it is clicked out

i have an menu with some values and i got someting hidden and while click on more button it shows like google more menu... if it is clicked out it is not hiding till the more menu is clicked once again
More<small>▼</small><div class="more list" id="one" style="display:none">test <span style="color:#329">|</span> test1 <span style="color:#169">|</span> test4</div></div>
Script:
function toggle(one)
{
var o=document.getElementById(one);
o.style.display=(o.style.display=='none')?'block':'none';
}
how to make it close while the mosuse clicks on any other place other than the menus
Try using the onblur event.
I see you've tagged this with jQuery, if that is an option, you can clear up the link a bit, like this:
More<small>▼</small>
And use unobtrusive script combined with event bubbling to your advantage, like this:
$(function() {
$(".more_link").click(function(e) {
$(this).next(".more").toggle();
e.stopPropagation();
});​​
$(".more").click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$(".more").hide();
});​
});
You can test it out here, this only closes the menu if you clicked neither the menu of the toggle, e.g. clicking one of the test links will not close it. If you want it to, just remove the $(".more").click(function(e) { e.stopPropagation(); }); portion.
It uses event.stopPropagation() to stop the click from bubbling up to document, which if happens (and would if you clicked anything else) triggers its click handler, closing all the .more elements.
I wouldn't use onBlur because it's not a good accessibility approach (for example if the user is using tab to navigate the page).
Look at this solution instead:
jQuery click event for document but ignore a div
Typically, I let the event bubble up to the 'body' or 'html' doc and check if the target is what i want (and/or isn't contained within what i want). If the event target is not contained within your menu, then perform your desired operation (in this case, hide the div).
i.e.
jQuery(document).ready(function(){
jQuery("html").bind("click", function(evt){
var $target = jQuery(evt.target);
var shouldShowMenu = $target.hasClass("menu_toggle");
shouldShowMenu |= $target.parents(".menu_toggle, .more_list").length;
if(!shouldShowMenu)jQuery(".more_list").hide();
});
});
NOTE: your markup would needs to be extended such that the "more" href becomes has a class attribute, class="menu_toggle"

Categories