Here is a Boostrap navigation bar, containing a dropdown menu, containing itself an <input>.
When I click on the dropdown menu, it is succesfully displayed. The value of the <input> is successfully changed to Bonjour but this <input> doesn't get the focus. Why ?
http://jsfiddle.net/rzsmdg4f/1/
How to give the focus to a input contained in a dropdown menu with .focus() ?
Code :
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<ul class="nav navbar-nav">
<li class="dropdown"> Dropdown<span class="caret"></span>
<ul class="dropdown-menu" role="menu" style="min-width: 250px;">
<li>
<div style="padding:4px 20px;">Link:</div>
</li>
<li>
<div style="padding:4px 20px;">
<input class="form-control" id="ha" type="text" placeholder="blabla" />
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
JS :
{
var maa = document.getElementById('maa');
console.log(maa);
maa.addEventListener('click', function () {
console.log($('#ha'));
$('#ha').val('Bonjour');
$('#ha').focus();
});
};
jsFiddle Demo
The element exists at the time of the click, so changing its value and logging it will properly show the current state of the element. However, it has not been displayed yet and as a result focusing it will not really have any effect. You could probably refactor some small snippet in the library to expose a hook that you could use to make your focus work. Or, you could make the observation that in the very next event handler the element will be visible and use a small timeout.
maa.addEventListener('click', function () {
console.log($('#ha'));
$('#ha').val('Bonjour');
setTimeout(function(){$('#ha').focus();},10);//timeout here
});
the simplest solution i came in mind is to just delay the focus. the reason its not focusing is because the element is not yet visible.
http://jsfiddle.net/xab7Leoq/
setTimeout(function() {
$('#ha').focus();
}, 100);
another solution is to find out when its getting visible, and then do it. it may be a better solution yet more complicated. :)
edit1: stopping propagation:
// Prevents the propagation
$('#ha').click(function(ev) {
ev.stopPropagation();
});
like in http://jsfiddle.net/xab7Leoq/
Figured I might as well post an answer, even if late... since this seems to work well and doesn't require setTimeout: http://jsfiddle.net/cvLbfttL/
$("#maa").focus(function () {
$('#ha').val('Bonjour');
$('#ha').focus();
return false;
});
$('#ha').click(function(){return false;});
The anchor "maa" gets the focus when clicked, and it happens after the click callback/event returns. So you can do your code in the focus event instead. I couldn't figure out how to tab to the anchor inside JSFiddle, but I assume the code would also run if you set the focus to the anchor using some other method, but that should be fine I think, maybe even nice.
An example using callback function. Man avoid to use setTimeout() function, because the results are unpredictable.
http://jsfiddle.net/v62tdn9z/
var $maa=$('#maa'), $ha=$('#ha');
$maa.mousedown( function () {
$ha.val('Bonjour');
$maa.mousemove(function () { $ha.focus(); });
});
Having a tabindex on the element could be the solution. This worked in my case.
Related
thanks for reading... I'll get right into the issue.
I have an onclick function attached to an image.
<div id="mercury" onclick="displayCreations()">
Javascript function:
function displayCreations(){
document.getElementById("projects").style.display = "block";
}
The div I'm displaying as a block is set to none once you arrive at the page. This function sets the display to block, which works.
I'm having trouble with making an onclick function for an image inside the div that sets the display value back to none. This doesn't seem to work with my current code...
HTML:
<div id="mercury" onclick="displayCreations()">
<img id="exit" onclick="hideCreations()" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />
<div id="projects">
<h3>No creator here, but it looks like you've found some his wonderous creations...</h3>
<ol>
<li>Project 1</li>
<li>Project 2</li>
<li>Project 3</li>
</ol>
</div>
</div>
Javascript:
function displayCreations(){
document.getElementById("projects").style.display = "block";
}
function hideCreations(){
document.getElementById("projects").style.display = "none";
}
When I run this site on google chrome and click the 'exit' button, nothing happens and nothing is displayed in the error messages.
This link leads you to a well-known site, Gyazo, where you can find a gif of what I see on my end.
Link: Link
I'd prefer a javascript solution for my current code, and perhaps you can explain to me why this is happening so I don't get into the same situation again.
It is caused due to event bubbling.Triggering an event on child propagates upward toward its parent.In your case click event on image also triggers click event on parent div.use event.stopPropagation() to prevent this from happening.
HTML :
pass the event as parameter to event listener function
<img id="exit" onclick="hideCreations(event)" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />
JS:
Capture the event and call it's stopPropagation method
function hideCreations(event){
event.stopPropagation();
document.getElementById("projects").style.display = "none";
}
A very useful solution from AL-zami. It's also useful outside the function e.g. onclick="event.stopPropagation();yourFunction(existing parameterset)". So You don't need to change yourFunction and it's parmeterlist, nor the other calls of it in the code.
It's even possible to create an extra container (e.g. div) around different events to prevent bubbling. e.g.:
<div id="picBigOLL" onclick="previousPict();">
<div id="picBigPlay" onclick="event.stopPropagation();">
<div id="playButsBox">
<div id="bPPlayL" onclick="diaPB(-1)">
⯇
</div>
<div id="bPPlayS" onclick="diaPB(0)">
||
</div>
<div id="bPPlayR" onclick="diaPB(1)">
⯈
</div>
</div>
</div>
My knowledge of javascript is close to none and I'm trying to have a div be replaced on click by another div.
<div class='replace-on-click'>
<h1>Click to Insert Coin</h1>
<div class='replaced-with'>
<div class='info-text'>
<h1>Title</h1>
<h2>Subtitles</h2>
</div>
<ul class='info-buttons'>
<li><a href='#' class='b1'>Buy Tickets</a></li>
<li><a href='#' class='b2'>Find Hotels</a></li>
</ul>
</div>
</div>
I'd like it so when you click "Click to Insert Coin", that will disappear and make the .replaced-with div take its place, hopefully with some kind of fade transition if possible. How do I go about doing this?
We will make use of jQuery because it helps us to get you desired behavior done in a few statements. So first include jQuery from somewhere in your head part of your HTML document.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Then somewhere include this Javascript code (e.g. create index.js and include it the way like the library code).
$(document).ready(function() {
$('h1').click(function() {
$(this).fadeOut(function() {
$('.replaced-with').fadeIn();
});
});
});
It does the following: When your document is ready, it adds an event handler on h1 waiting for clicks. On click, it first fades out the h1 and when it's done, it fades the other element in.
In your HTML document, include the hidden attribute to the object that should be hidden initially.
<div class='replaced-with' hidden>
Here you can find it working as well: http://jsbin.com/cuqoquyeli/edit?html,js,console,output
I'm having a slideDown function on my site. But somehow it doesn't work the first time when you click it. So I need to click two times to make the function work. What can possible be wrong?
I also want the div to slide up when I click on the button again, don't know how I will do this. I tried using slideToggle but it just ended up with the div going up and down a couple of times before closing. Even for this I needed to click two times.
Here is my JS:
function showCart() {
$("#rollDown").click(function() {
$("#shopping_cart_page").slideDown();
});
/* not relevant for this */
emptyBag = document.getElementById("emptyBag");
emptyBag.addEventListener("click", emptyCart);
}
And here is my HTML:
<div id="navbar">
<ul>
<li>Products</li>
<li>About</li>
<li>Giveaways</li>
<li>Contact </li>
<li><a id="rollDown">Shopping Bag</a></li>
</ul>
</div>
Here's a simple example:
jQuery:
$(document).ready(function(){ // Just adding the click event inside the document ready method should do the trick for you.
$("#rollDown").click(function() {
$("#shopping_cart_page").slideToggle();
});
});
HTML
<input type="submit" id="rollDown" value="Toggle"/>
<div id="shopping_cart_page">Hi</div>
Fiddle: http://jsfiddle.net/64gn1unk/
My code is simple. It can be found at this jsFiddle:
<div id="tabs">
<ul>
<li>About</li>
<li>Fine Print</li>
<li>Location</li>
</ul>
<div id="highlights">
highlights
</div>
<div id="fineprint">
FiNEPRINT
</div>
<div id="location">
<ul>
<li>
<address>ADDRESS</address>
</li>
<li>
MAP
</li>
</ul>
</div>
<button class="btn-placeorder"><span id="maplink">View map</span></button>
<script>
$(function(){
$("#tabs").tabs();
});
$('#maplink').click(function(){
$("#tabs").tabs("option","active",2);
});
</script>
On Firefox you will notice, even in the fiddle the tabs don't change when the view map button is clicked.
I don't work with javascript much but I'd love to gain a better understanding of how to diagnose and solve these problems. Why is this happening, how can I solve it and how can I better educate myself?
First debugging tip: use tools. Most browser's nowadays include debugging tools you can call with F12. In Firefox, the short-cut is Cmd+Opt+K or Ctrl+Shift+K though I recommend you open the add-on manager and install Firebug.
Second tip: check whether your code runs. The console API is a good start:
$('#maplink').click(function () {
console.log("Button clicked");
$("#tabs").tabs("option", "active", 2);
});
Nothing gets printed so your event is not being called. We can see it isn't attached directly to the button but to an inner <span>:
<button class="btn-placeorder"><span id="maplink">View map</span>
</button>
So we wonder: is there something wrong with onclick events on spans?
$("span").on("click", function(){
console.log("click on span: %o", this);
});
Nothing printed, so there's apparently an issue. It is possible that the button is catching the onclick event?
<button class="btn-placeorder"><span id="maplink">View map</span>
</button><span>Test span</span>
click on span: <span>
So that it's! Weird... Well, why do you need a <span> in the first place?
$('.btn-placeorder').click(function () {
console.log("Button clicked");
$("#tabs").tabs("option", "active", 2);
});
It works! All we need now is some cleanup, such as assigning a proper ID to the <button> and getting rid of the redundant <span>.
Your #maplink selector matches your inner <span> element, not its <button> parent.
Try writing:
<button id="maplink" class="btn-placeorder"><span>View map</span></button>
Instead of:
<button class="btn-placeorder"><span id="maplink">View map</span></button>
Replace the id of the span with the actual class of the button, like this:
$('.btn-placeorder').click(function(){
$("#tabs").tabs("option","active",2);
});
Even if other answers are also correct, there could be another problem, the on click event handler registration is happening outside dom ready.
Try
$(function() {
$("#tabs").tabs();
$('#maplink').click(function() {
$("#tabs").tabs("option", "active", 2);
});
});
Demo: Plunker
I am trying to use JQuery toggle, so when a user clicks the info icon, the hidden div containing item information is shown / hidden. For some reason it is not working for me.
While trying to debug, I noticed that show(), correctly shows the target element that I would like to toggle. However, when I replace show() with toggle(), it does not work and does not return any error.
I was wondering if someone can help me identify the cause of this problem.
My Markup
<div class="option">
<div class="prod-text">Toy Whistle </div>
<div>
<img class="info-icon" src="Info-icon.png">
</div>
<div class="option-info" style="display:none;">
<div>
<div class="price-text">Price: $100</div>
<div class="prod-id-text">Item Number: 231912</div>
<div class="quantity-text">Quantity: 72</div>
</div>
</div>
</div>
JQuery (does not work)
$(".info-icon").click(function(){
$(this).parent().parent().find('.option-info').toggle();
});
JQuery (works!)
$(".info-icon").click(function(){
$(this).parent().parent().find('.option-info').show();
});
Many thanks in advance!
Perhaps the click event handler is getting bound twice, and thus fire twice for each click. The show() would work fine in this case, but the toggle() would show and then immediately hide the element each time you click. Try this:
$(".info-icon").click(function(){
console.log('click handler fired');
$(this).parent().parent().find('.option-info').toggle();
});
And run this with Web Inspector or Firebug enabled to see how many messages are logged for each click.