I am using CSS to apply a background image to a div tag that wraps all of the content on a website.
<div id="mainBack">
<%-- All other content goes here --%>
</div>
And the CSS id with the background property...
#mainBack
{
background: url(../images/background.jpg) repeat-x top;
padding: 15px 0 20px 0;
}
PROBLEM:
I'm trying to figure out how to open a new browser window to a different URL whenever the background image is clicked upon. I have tried doing this using jQuery, but the manner in which I implemented it actually causes every click on anything in the website to open a new window. The jQuery click event that does this - although incorrectly - is below:
$('#mainBack').click(function () {
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
});
Any suggestions on how I can go about implementing this behavior in a fashion that actually works?
You can stop the propagation of click events for elements on top of your #mainBack element.
For example:
<div id="mainBack">
Some Link
</div>
<script>
$('a').on('click', function (event) {
event.stopPropagation();
});
</script>
This will make it so any link clicked on will not allow the event to bubble up to any ancestor elements. Which in turn will make detecting a click on the #mainBack element possible.
You will have to stop the propagation of the event on any element you want to be clickable without opening the popup window.
Also, note that .on() is new in jQuery 1.7 so if you're using an older version, change .on() to .bind().
Update
You can also use the event object inside your event handler to check if the targeted element is the #mainBack element:
$('#mainBack').click(function (event) {
if (event.target.id == 'mainBack') {
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
}
});
Here is a demo of using event.target: http://jsfiddle.net/j5NuW/ (notice the event handler is attached to the body element but the alert only shows if you click the #mainBack element)
You can check if the clicked element was the div or something else by adding one line of code, and the event parameter to the function:
$('#mainBack').click(function (event) {
if(event.target==this)
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
});
Related
Got some simple functionality set up on a page. Initially I want to replace default action of a hyperlink click with some functionality which will display an overlay.
After the overlay is displayed I want to remove the event listener I have placed on the hyperlink so it reverts to what it was previously (i believe there is another event listener on here, I dont want to remove this one while removing mine). Within the overlay is another button which when clicked, should trigger the initial functionality of the button.
Ive tried the .off() jquery method, however this seems to prevent the ".mmclose" button from working.
Not quite sure where i am going wrong with this..
// placing event listener on initial link
$("#utility_0_HyperLinkLogout").click(function() {
// removing event listener(?)
$("#utility_0_HyperLinkLogout").off("click");
// preventing default button behavior
event.preventDefault();
//overlay replacing original content
I62originalContent.hide();
$("#mmi62wrapper").fadeIn("slow", function() {
// new event listener placed on button within overlay (as callback)
$(".mmclose").click(function() {
//new button should now trigger original buttons original functionality?
$("#utility_0_HyperLinkLogout").trigger("click");
})
})
});
You can use jQuery .one method to attach a handler which will be executed only once. You don't need to worry about removing this handler anymore.
Check this example:
$(".myClass").click(function() {
this.innerText += "!";
});
$("#myId").one('click', function() {
this.innerText += "?";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="myClass" id="myId">Click me twice</button>
In this example, clicking the button keeps adding "!", while "?" is only added once. Other handlers are not affected.
I'm using jQuery 2.1.3. I try to build a button that will show/hide content on click. I also want to hide the content when there's a click on a wrapping container (in my application it's the document itself, but I used a regular div in my example below). As there is some more logic to handle I'm also making use of custom events that I fire via .trigger().
This works fine but I have a problem. When I show the hidden content I apply an eventlistener to document to hide the content when the user clicks anywhere on it. This eventhandler is fired straight after the content is shown resulting in my content gets hidden immediately.
I can only get around this by using $evt.stopPropagation() in my toggle buttons event handler. But that's no solution for me as I need the event to bubble up as other elements listen for that.
Heres the simplified HTML:
<div id="document">
<button id="btn" type="button">Toggle</button>
<div id="content" class="hidden">Hidden Content</div>
</div>
And heres the JS to this:
//trigger custom show event
var show = function () {
$("#document").trigger("show");
};
//trigger custom hide event
var hide = function () {
$("#document").trigger("hide");
};
//handle custom show event
$("#document").on("show", function () {
$("#content").removeClass("hidden");
$("#document").on("click", hide);//add listener to container, fires immediately
});
//handle custom hide event
$("#document").on("hide", function () {
$("#document").off("click", hide);//remove listener from container
$("#content").addClass("hidden");
});
//on toggle button click call custom events
$("#btn").click(function ($evt) {
//$evt.stopPropagation(); would work but event should propagate
$("#content").hasClass("hidden") ? show() : hide();
});
JSFiddle
What could I do about this? Stopping event propagation on toggle button click would show my content but i need this event to bubble up as there are other elements around waiting for that. How could I avoid that the applied event listener on document fires immediately?
PS: jQuerys .show()/.hide() functions are no alternative for me.
The premise of what I'm trying to do is use jQuery to start a CSS transition to open and close a search box.
User clicks magnifying glass icon, box opens, user clicks anywhere on the page but the search form, box closes.
To close, using this:
$('body *').not('#header-search, #header-field, #header-submit').click(function () {
And different variations of the answer found here: jQuery - Select everything except a single elements and its children? without success.
Clicking on the input#header-field always closes the box.
Pen Here:
http://codepen.io/anon/pen/RNbmwr
Thanks for reading.
Your code is very aggressive (it gets applied to all elements, so inner element to those in the .not() will trigger it).
It is better to delegate the closing of the box to the body (since click events bubble up), and manually cancel any event that occurs under the forbidden list.
$('body').on('click', function(){
// code for closing box here
});
$('#header-search, #header-field, #header-submit').on('click', function(){
return false; // stop bubbling of event
});
And since in your example the #header-field and #header-submit are descendants of header-search you only need to cancel the bubbling on that
$('#header-search').on('click', function(){
return false; // stop bubbling of event
});
Demo at http://codepen.io/gpetrioli/pen/XJrwXO
Try the jQuery toggle() function:
<script>
$( "button" ).click(function() {
$( "p" ).toggle( "slow" );
});
</script>
Substitute the id for your magnifying glass for "button" and change the paragraph -- $("p") -- the search controls you want to show/hide. Toggle changes the visibility of the indicated id or class. If it is initially hidden, mouse click will make it visible; if initially visible, mouse click will hide it.
Finally, change the speed of the transition if you don't want it to move "slow"
A more complete explanation of toggle() is available at http://api.jquery.com/toggle/
There are many elements on the page. Some of them may contain or be contained by the elements you name. So they will still trigger the event.
Instead, bind a single event handler:
$("body").click(function(evt) {
and check if you clicked on one of the elements:
if( $(evt.target).parents("#header-search").length > 0) {
cancelling the handler if so:
return true;
}
Perform the actual event otherwise:
doSomething();
});
Here is my code below I'm trying to hide addstuff id div when clicked out of it. I tried body click event but it was useless. So I need a trigger event like blur. But It doesn't work for both blur and focusout events.
$(document).ready(function() {
$('#addstuff').blur(function () { $('#addstuff').fadeOut() })
})
There is no blur event for div. You can create that effect using the click event of body.Note that you should exclude that div from the click event
$(document).ready(function () {
$("body").not("#addstuff").click(function (e) {
$("#addstuff").fadeOut();
});
});
Fiddle
Edit
As #TrueBlueAussie suggested, it would be better to use document instead of 'body' for the click event handler:
$(document).not("#addstuff").click(function (e) {
$("#addstuff").fadeOut();
});
There's no way you can use .blur with a div, it has to be with some input field.
You can always use mouse events like
$(document).ready(function(){
$("#addstuff").mouseleave(function(){
$(this).remove();
});
});
http://jsfiddle.net/asrF2/
You can also use the HTML5 global attribute contenteditable (don't forget to set it true or false)
<div id="#addstuf" contenteditable="true">bla bla</div>
I don't recommend this that much, because of mobile browsers' compatibility.
divs have no focus and blur events, but you can add a contenteditable attribute so that you can type in that div, so the blur actually gets fired:
<div id="addstuff" contenteditable></div>
Then your jquery code works.
You can add additional functions to prevent people from actually typing in that div.
Alternatively you can use the .mouseleave() or .mouseout() event.
div element cannot be focused on so the blur function of jquery cannot be applied to it. See existing answers from our Stack Exchange buddies below for elements that focus can be applied on.
Which HTML elements can receive focus?
I am using Jquery text editor and while editing I want to drag and drop images on the editor. But the problem is that after dropping img on jqte the mouseenter event does not fire.
$(document).ready(function() {
$('.jqte_editor img').on('mouseenter', function() { alert("hello");
$(this).before("<div style='position:absolute'><input type='textbox'>
</input></div>"); });
});
the editor main container
<div class="jqte_editor" contenteditable="true"><img ></img></div>
Ah, I misunderstood you! Disregard my previous answer.
When you use on() on the .jqte_editor img object, you're attaching the mouseenter event to all <img> elements within the <div>, and these events are attached at the exact time that on() is called. (This is called a direct event handler.) So, when you call it while the <div> is blank, there are no <img>s to attach the event to.
That's why, when you re-open the editor that has images already in it, your on() statement actually has images to attach the event to this time.
What you need is a delegated event handler. You would use this script:
$(document).ready(function() {
$('.jqte_editor').on('mouseenter', 'img', function() {
alert("hello");
$(this).before("<div style='position:absolute'><input type='textbox'></input></div>");
});
});
Basically, you attach the event to .jqte_editor itself. Then, you see that second argument in the on()? That selector means that this becomes a delegated event handler. It will trigger on any <img> within .jqte_editor, whether that image is already present or will be added dynamically in the future.
Your code is valid, except for one issue: you're attaching the mouseenter handler to the selector .jqte_editor img. You have an img in your jqte_editor div, but since it has no src (nor does it have any CSS giving it width or height), it's an image of 0 width and 0 height. So, the mouseenter event can't trigger on that img because it isn't being rendered.
I used your code and attached the event to .jqte_editor instead, and it works as expected. Look at this fiddle to see it working.
Although, this event will fire whenever the mouse enters the div, even if the user isn't dragging anything. So, the following script detects when the content of the div is changed, and only fires if an image has been added (demo here):
var contents = $('.jqte_editor').html();
$(document).ready(function() {
$('.jqte_editor').on("mouseenter", function() {
if (contents != $(this).html()) {
var to = contents.length;
var diff = $(this).html().substr(length);
if (diff.substr(0,4).toLowerCase() == "<img") {
alert("Image added.");
$(this).before("<div style='position:absolute'><input type='textbox'></input></div>");
}
}
});
});