How to make a div click-through but hover-able? - javascript

I need to make a div so that when the cursor hovers over it then I can detect it (using javascript) but I want to make it so that you can click through the div to the elements underneath. Is there a way to do this?
Thanks

Edit
As far as I'm aware, and through my quick searches, I do not believe that you are able to do this, if you can it wouldn't be easy and or very practical I wouldn't think.
old
Using jQuery:
$(document).ready(function(){
$("body").on("hover", "div", function(){
//do whatever you want on hover
});
$("body").on("click", "div .child-class", function(){
//do whatever on click
});
});
If this doesn't answer your question and do what you want, let me know what more specifically why it doesn't.

There are multiple solutions for this depending on your problem.
I will start with some assumptions:
1. You are the owner of the page (you know what happens there);
2. You know what element is beneath the clicked element.
For this case check this code:
//function executed when you click on element with id: beneath
function clickOnBeneath() {
alert("beneath click");
}
//function executed when you click on element with id: above
function clickOnAbove() {
var beneathEl;
beneathEl = document.getElementById("beneath");
beneathEl.click();
}
//attach click event on element with id: above and beneath
function attachClickOnElements() {
var aboveEl,
beneathEl;
aboveEl = document.getElementById("above");
aboveEl.addEventListener("click", clickOnAbove, false);
beneathEl = document.getElementById("beneath");
beneathEl.addEventListener("click", clickOnBeneath, false);
}
attachClickOnElements();
and also working example: http://jsfiddle.net/darkyndy/xRupb/
If you don't know what element is beneath it then I will try to find some code as I wrote a couple of years back something like this, as start point you can check getClientRects() function that is available on HTML elements (documentation: https://developer.mozilla.org/en-US/docs/DOM/element.getClientRects )

Related

Jquery on mousedown not working on dynamically generated elements

So i'm trying to create a js/css "wave game" like tower defense ones.
When all the pre-generated enemys from first wave are dead, it spawns the second wave and so on.
So far so good.
The problem is that i just can't attack mobs dynamically spawned within second wave.
I used to try .live() in similar cases, but its deprecated, so i'm trying .on(), as instructed
$('.enemy').on('mousedown' , function(event) {
//attack code
}
Its working fine for initial mobs (1st wave) but it still just not working on dynamic mobs (>= 2nd wave)
Help, guys, please?
You need to specify an element that is already there when the DOM is created. In the parameters, you specify the elements you want to add the mousedown method. By simply assigning $('.enemy'), it will attach the method to those that are already present in the DOM.
$('body').on('mousedown', '.enemy', function(event) {
//attack code
}
As Wex mentioned in the comments, instead of writting $('body') you should use the container's name (the container which wraps the .enemy elements. This way, when a .enemy element is added, the event doesn't need to bubble all the way up to the body tag.
The binding '.on()' works only with the content that created earlier then the script ran.
So one solution could be you bind the event to the parent element.
$('.PARENT_ELEMENT').on('mousedown', '.enemy', function(event){
// your code here
}
That should do it.
I made this google like drop down suggestions search box and I faced a problem similar to yours where there was suggestions disappearing before the re-direct happened. I overcame it by using and modifing vyx.ca answer:
var mousedownHappened = false;
var clicked_link;
$("#search-box").blur(function(e) {
if (mousedownHappened)// cancel the blur event
{
mousedownHappened = false;
window.location.href = clicked_link;
} else {
// no link was clicked just remove the suggestions box if exists
if ($('#search-btn').next().hasClass('suggestions')) {
$(".suggestions").remove();
}
}
});
//attaching the event to the document is better
$(document).on('mousedown', '.suggestions a', function() {
clicked_link= $(this).attr('href');
mousedownHappened = true;
});

Toggling one thing with two different elements

In my previous question I asked about how can I toggle a textarea with a paragraph. I got the answer. Now I want to do the opposite of it. First I was showing the already hidden textarea + 2 buttons by a click of a hyperlink. Now on the click of one of the buttons I want to hide the text + 2 buttons and show the paragraph that was first already shown.
I have tried this JS so far but it's not working:
$(document).ready(function () {
$(".no_link").click(function (e) {
e.preventDefault();
});
$(".edit_offer").on('click', function () {
toggleEditPanel($(this));
});
$("#cancel_edits").on('click', function () {
$(this).closest("button").hide();
$(this).closest("textarea").hide();
$(this).closest("p.content").show();
});
});
function toggleEditPanel(link) {
link.parent().parent().parent().find("textarea").toggle();
link.parent().parent().parent().find("button").toggle();
link.parent().parent().parent().find("p.content").toggle();
}
But its not working. How can I solve this error?
If I am trying to call the function toggleEditPanel() again. Its not working then aswell.
You can find the markup in the fiddle. Here's the fiddle.
UPDATE 1:
Just came up with a solution. I can use the $.siblings() function to toggle the elements beside the button. Still, is there any better solution?
Here's the code that I came up with:
$("#cancel_edits").on('click', function () {
$(this).hide();
$(this).siblings("button").hide();
$(this).siblings("textarea").hide();
$(this).siblings("p.content").show();
});
UPDATE 2:
The problem in the above code is that if there are more than one panels like this then the code is not working. How can I solve that issue aswell?
You are using Id for selector $("#cancel_edits") .
Id selectors returns only first element , so if there are multiple pannel it will work only for first.
Instead give some class name and use it for selector. Further you can use chaining and caching in your code for better performance.
$(".cancel_edits").on('click', function () {
var elm=$(this);
elm.add(elm.siblings("button,textarea")).hide();
elm.siblings("p.content").show();
});
I would recommend referencing your elements by ID:
$("#cancel_edits").on('click', function () {
$('#save_edits').hide();
$('#edited_content').hide();
$(this).hide();
$("p.content").show();
});
JSFiddle
The great thing about using IDs is that you are guaranteed they are unique - no need to use closest() to find the element you want. If, however, you're using classes instead, closest() might be necessary or helpful.

jQuery: mouseover makes image visible that has the same last 4 numbers in their id as the trigger

I am currently working on a website and got stuck with the following problem:
On the website I have small dots (images) with the ids "dot0001", "dot0002", "dot0003", etc. . I also have hidden images (visibility:hidden) with the ids "info0001", "info00002", "info0003", etc.
I am looking for a jQuery solution. What I need is a code that allows the following events:
When users move the mouse over "dot0001" the image "info0001" becomes visible and when they leave "dot0001", "info0001" becomes invisible again. Same applies to "dot0002"-"info0002" , "dot0003"-"info0003" etc. So only the info-images with the corresponding 4 digit number become visible.
I gave it endless tries but got nowhere and there is not even a point in pasting my code.
Any help appreciated!
Something like this should work (though untested):
$('[id^="dot"]').on({
mouseenter: function(e) {
var infoId = this.id.replace('dot', 'info');
$('#' + infoId).show();
},
mouseleave: function(e) {
var infoId = this.id.replace('dot', 'info');
$('#' + infoId).hide();
}
});
That uses an attribute-starts-with selector to select all elements with an id beginning with "dot", then binds the event handlers to them. The event handler functions themselves simply replace the "dot" part of the id with "info" to form the correct new one, then show or hide the element as appropriate.
Don't forget to wrap that code in a DOM ready event handler so that it executes once the elements actually exist, otherwise it won't work.
Get all elements which id starts with "dot" and show/hide related "info" on mouseover/out:
$("[id^=dot]").hover(
function(){
$("#info" + this.id.substring(3)).css({"visibility":"visible"});
},
function(){
$("#info" + this.id.substring(3)).css({"visibility":"hidden"});
}
);
http://jsfiddle.net/EGBnR/

jQuery click() not working on replaced html

I am trying to create a go-moku game using jquery,php, and mysql database.
I have a ajax function that updates the a board every second if needed.
var turnCount = -1;
setInterval(function(){
$.get('includes/boardControl.php',{turn: turnCount }, function(data){
if(data != "")
{ $("#board").html(data);
turnCount = $("#turnCount").text();
$("#turnCount").text("")
}
});
}, 1000);
This works just fine, it checks the database to see if turn has been incremented and replaces the board if it has. Now what I want to ultimately do is create a click function that use Ajax to update the board and turn count in the database. I am hoping to somehow use the N'th selector do determine what square I'm clicking on.
I have several questions.
1) My click function right now is
$(document).ready(function() {
$("td > img").click(function(){
alert("clicked");
});
});
as of right now it works on a extra test table I wrote into the html, but not on the table created with the previous function. What am I doing wrong?
2) The tutorials I've looked at so far dictate that I should write code in the following way.
$(document).ready(function() {
//code here
});
When i asked a question last night, I was told that I was over complicating things with my functions. So when should i use a document.ready function and when not? And is it fine to put all of my scripts into one document.ready function or should I have multiple?
3)
Once I get the click image to work I am hoping to send a X,Y coordinate to the server and change that corresponding spot on the board. How would I determine what cell in the table is clicked in order to know what coordinates to use? (or is there a much easier way?)
sounds like you need to change
$("td > img").click(function(){
alert("clicked");
});
to
$("td > img").live('click',function(){
alert("clicked");
});
Edit: For jQuery 1.9 and later you can do:
$("#board").on('click', 'td > img', function(){
// handle click
});
The $(document).ready() function only fires when the page first loads - in order to make this work try something like this:
function bindClicks() {
$("td > img").click(function(){
alert("clicked");
});
}
$(document).ready(bindClicks);
This will allow you to call bindClicks() later on if need be to bind the click events of a new table.
1) Are you re-wiring the click event after the ajax content loads?
The $(document).ready function will fire as soon as the page is fully loaded, but won't fire after ajax calls. So you will need to re-wire the click event after every ajax call:
2) KISS. Keep it as simple as possible. If you have 50+ lines inside a document.ready statement you might want to create some functions.
3) The best way to accomplish this might be to assign a specific ID to each cell and capture that in the click event. You can then pass that to the server and update the specific cell on the return.
Are you sure JQuery is matching you query:
$("td > img")
I would load firefox with firebug and check that your actually getting match first. The second table your creating may have a slightly different structure then you expected and firebug can show you the exact structure also.
Goodluck.

Javascript GUI issues with event bubbling

I am trying to setup a fairly simple (imo) Javascript GUI, and am running into issues. I'm using jQuery. Here's what I want to do:
Have a bunch of squares next to some text, like this:
[ ] Text next to square
[ ] Text next to square 2
[ ] Text next to square 3
[ ] Text next to square 4
When you click one of the squares, an absolutely positioned floating div shows up. That floating div has some interface options.
At this point, if the user clicks anywhere OUTSIDE the floating div, the div should disappear. If the user clicks another box, the original div should disappear, and a new one should appear.
I am able to get the floating divs to show up correctly, but I'm having trouble hiding them. What I'm currently doing is attached a click handler to $(document) in the function that show the floating div. Simplified code is below:
show(jqueryObj)
{
jqueryObj.show();
$(document).one("click", function () { jqueryObj.hide(); });
}
(Show is bound to a lick on one of the [ ] boxes elsewhere)
The problem I run into is that the click event seems to bubble up, and function () { jqueryObj.hide(); } is executed immediately. I've tried returning false in show(), but that didn't seem to resolve the issue. What should I be doing here?
$(document).click(function(e) {
e.stopPropagation();
var el = $(e.target);
alert( el.get(0).nodeName );
});
Off the top of my head, are you looking for something like this? I ignored your code because it isn't standard jQuery and a bit abstracted.
It could be that your click handler is getting called for the same click that it's added in. If that's the case then you would fix it by stopping the original click from bubbling (e.g. whatever is calling your function show).
Another option is to hack it:
show(jqueryObj)
{
jqueryObj.show();
setTimeout(function() {
$(document).one("click", function () { jqueryObj.hide(); });
}, 0);
}
If I'm getting you right, your floating div disappears when you interact with it because that document click catches the interaction and hides it. If thats the case you need to check the target of your event and exit out if it is the floating div. Something like this:
$(document).click(function(e) {
var target = $(e.target);
if (target.is("#floatingDiv")) return;
jqueryObj.hide();
});
Hope that helps
Edit: one thing to note is that you can check multiple conditions in the .is() call. So for example you could check for clicks on the floating div AND on one of your activation boxes:
if (target.is("#floatingDiv, .activateBox")) return;

Categories

Resources