JQuery: Click Class Reaction - javascript

$(document).ready(function() {
// ............. Your jQuery Code goes here .............
//var myArray1 = new Array( "img1", "img2" , "img3", "img4");
var numImg = $('#thumbNail img').length; //number of images
var num = 0;
var curImg = 0;
//Prevent Image Dragging
$("img").bind('contextmenu', function(e) {
return false;
});
//Prevent Right Click on Mouse
$("img").bind("mousedown", function(e){
return false;
});
$(".leftThumbNail").live("click", function(){
alert("HY");
});
});
I am trying to have it react to when ever I click on images inside class "leftThumbnail". This class contains 2 images on the left panel. Whenever I click any of the images from that class, nothing seems to happen.
I also tried:
$(".leftThumbNail").click(function() {
alert("HEY");
});
In my "leftThumbNail" class I have the following:
<div class="leftThumbNail">
<img id = "img1" src="img/thumb/image1.jpg" class = "image1Position" alt="Image 1">
<img id = "img2" src="img/thumb/image2.jpg" class = "image2Position" alt="Image 2" >
</div>

Ok try this:
$('img').on({
contextmenu:function(e) {
e.preventDefault();
},
click:function(e){
if(e.which === 3){
e.preventDefault();
}
},
dragstart:function(e){
e.preventDefault();
}
});
$(".leftThumbNail").on('click', function(){
alert('HY');
});
This does the following:
Kills right-click by checking e.which to be specific to right-clicks
updates to .on(), the modern version of what you wanted to do
Combines your handlers for 'img' into a single .on() declaration
To consolidate it even more:
$('img').on({
contextmenu:function(e) {
e.preventDefault();
},
click:function(e){
if(e.which === 3){
e.preventDefault();
} else if($(this).hasClass('leftThumbNail')){
alert('HY');
}
},
dragstart:function(e){
e.preventDefault();
}
});
No more extra handlers ... all handled in one now!
EDIT Modified to include prevention dragging (performed by using dragstart handler). Also changed return false to the more proper e.preventDefault() to allow for bubbling.

Related

addEventListener for the same event

So I have a few div tags that I have currently hidden, and I want to display them one after the other by hitting the enter key.
What I want to happen: I hit enter and the first div tag is revealed, and then I hit enter a second time to see the second div tag.
What is happening instead: I hit enter once and both div tags show up.
In this case, the first div tag I want to reveal is "intro", and the second is "body". I am running this website on jsbin, and I am using chrome, if that helps.
This is my JavaScript:
//***********************************************************
// BODY MODULE
var bodyController = (function(){
var enterBool;
var reveal = function(){
if(enterBool){
document.getElementById("evidence").style.display = "block";
enterBool = false;
}
};
var enterListen = function(){
document.addEventListener("keydown", function(event){
if(event.keyCode === 13){
document.addEventListener("keyup", function(event){
if(event.keyCode === 13){
enterBool = true;
reveal();
}
});
}
});
};
return{
enterBoolBody: enterBool,
enterListenBody: function(){
enterListen();
}
}
})();
//***********************************************************
// INTRO MODULE
var introController = (function(){
var enterBool;
var reveal = function(){
if(enterBool){
document.getElementById("body").style.display = "block";
enterBool = false;
}
};
var enterListen = function(){
document.addEventListener("keydown", function(event){
if(event.keyCode === 13){
document.addEventListener("keyup", function(event){
if(event.keyCode === 13){
enterBool = true;
reveal();
}
});
}
});
};
return{
enterBoolIntro: enterBool,
enterListenIntro: function(){
enterListen();
}
}
})();
//***********************************************************
// CONTROL MODULE
var controller = (function(introCtrl, bodyCtrl, evidenceCtrl, infoCtrl,
conclusionCtrl){
var eventListeners = function(){
introCtrl.enterListenIntro();
bodyCtrl.enterListenBody();
};
return{
init: function(){
eventListeners();
}
}
})(introController, bodyController, evidenceController,
infoController, conclusionController);
//***********************************************************
controller.init();
I think you might be over engineering this a bit. All you need is an event listener to check for enter. Then you check if the first div is shown, if not show it. If the first div is shown check if the second div is shown and show it.
Quick note, no IE9 support for classList if that's important to you.
https://caniuse.com/#feat=classlist
(function(window, document, undefined)
{
document.addEventListener('keyup', showDivs, false);
})(window, window.document);
function showDivs(event)
{
event = event || window.event;
var divsToShow = document.getElementsByClassName("Display-Div");
for (var i = 0; i < divsToShow.length; i++) {
if (!divsToShow[i].classList.contains("Block")) {
divsToShow[i].classList.add("Block");
break;
}
}
}
.Hidden {
display: none;
}
.Block {
display: block;
}
<div class="Hidden Display-Div">This</div>
<div class="Hidden Display-Div">Now</div>
<div class="Hidden Display-Div">Works</div>
<div class="Hidden Display-Div">With</div>
<div class="Hidden Display-Div">Any</div>
<div class="Hidden Display-Div">Div</div>
<div class="Hidden Display-Div">With</div>
<div class="Hidden Display-Div">Class</div>
<div class="Hidden Display-Div">Display-Div</div>
You can put the ids of your divs in an array, or you could assign a common class to all divs that you want to appear one by one. Assuming the first, this code simply grabs the id of the next div to display from the array and increments the counter. You could add more divs to the array and it would work.
var divs = ["evidence", "body"];
var counter = 0;
document.addEventListener("keyup", function(event){
if(counter < divs.length && event.keyCode == 13){
document.getElementById(divs[counter]).style.display = 'block';
counter++;
}
});

button continually only fire once

If keep clicking the same buttons then only fire once. sample: https://jsfiddle.net/h4wgxofh/, For example, if click1 clicked then 2nd time or more times clicks should stop firing, the same as click2 however, if I click the same button, it always fires. Also I want links only trigger once but becomes available if other buttons being clicked. (considering if more buttons) Thanks
HTML
<div class="wrap">
Click1
Click2
</div>
Script
var clicked = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
clicked = true;
if(clicked = true){
console.log($this.text());
clicked = false;
}
});
I'm probably missing something here, but why not just bind the event to every link in .wrap and unbind it on click like this :
$('.wrap a').on('click', function(){
console.log($(this).text());
$(this).unbind('click');
});
See this fiddle
Edit : after your comment on wanting one link to be rebound after cliking on another, even though it might not be the cleanest solution, this does the job :
var onclick = function(){
var $el = $(this);
console.log($el.text());
$('.wrap a').off('click', onclick);
$('.wrap a').each(function(id, link){
if($el.text() != $(link).text())
$(link).on('click', onclick);
});
}
$('.wrap a').on('click', onclick);
Fiddle again
See the following code
var clicked1 = false;
var clicked2 = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
var clickOrigin = $(this).text();
if(clickOrigin == 'Click1' && clicked1==false){
console.log("Click 1 clicked");
clicked1 = true;
}
if(clickOrigin == 'Click2' && clicked2==false){
console.log("Click 2 clicked");
clicked2 = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
Click1
Click2
</div>
Also you can find the jsFiddle.
You need to Distinguish between two links(i used text here you may put whatever scenario ) see this example it may help:-
var clicked1 = 0;
var clicked2 = 0;
$('.wrap').on('click', 'a', function() {
var $this = $(this);
var $text = $(this).text();
//Click2
if ($text == 'Click1') {
clicked1 += 1;
if (clicked1 == 1) {
console.log($text);
} else {
return;
}
}
//Click2
if ($text == 'Click2') {
clicked2 += 1;
if (clicked2 == 1) {
console.log($text);
} else {
return;
}
}
});
Full Demo
To disable both buttons after first click, try:
var clicked = false;
$('.wrap').on('click', 'a', function(){
let $this = $(this);
if( !clicked ){
console.log($this.text());
clicked = true;
};
});
To disable each button after first click, try:
$('.wrap a').each(function() {
let $this = $(this);
$this.disabled = false;
$this.on('click', function() {
if ( !$this.disabled ) {
console.log($this.text());
$this.disabled = true;
};
});
});
Every time someone clicks one of the buttons, your script is setting clicked from false to true, checking if the value is true, then setting it to false again. You need to format it like this if you only want the buttons to fire once (obviously you'd have to duplicate this specifically for each button with different IDs):
var clicked = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
if(clicked == false){
console.log($this.text());
clicked = true;
}
});
try this ,much simpler and this will be more useful if you have multiple click buttons
if you had implemented some other way ,this will worth a try
<div class="wrap">
Click1
Click2
</div>
$('.wrap').on('click', 'a', function(){
var $this = $(this);
if($this.attr("data-value") == ""){
console.log($this.text());
$this.attr("data-value","clicked")
}
else{
console.log("Already clicked")
}
});
Fiddle
Instead of putting code on click just on first click disable anchor tag this serve the same thing you wants just find below snippet for more information using this we can reduces round trips to the click functions as well
$('.wrap').on('click', 'a', function(){
$(this).addClass("disableClick");
});
.disableClick{
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
Click1
Click2
</div>
I think you can disable anchor link after one click like this
<div class="wrap">
Click1
Click2
</div>
I think you can disable anchor link after one click like this
<div class="wrap">
Click1
Click2
</div>
$(function () {
$('#click1').on("click", function (e) {
$('#click1').on("click", function (e){
e.preventDefault();
e.preventDefault();
});
});
I think its help you.
Just use $(".wrap").one('click', ....
Read the jquery API documentation.

Need to simulate keypress jquery

I have a function that uses the value of a textbox (prodinput) to hide/show links in a dropdown list. It works when a user types in a string manually but when I want to auto-populate the value by passing a url parameter I'll need to trigger a keyup or keydown to get it to call the function.
Here is the function that does the search (located in the core.js):
prodinput.on('keyup, keydown',function() {
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
});
Here is the function I'm using to trigger the function above (located on the page I'm trying to run it on.
$(function(){
$target = $('.browse-products .display');
$target.val($trimmed);
$('.browse-products').addClass('active');
$target.focus();
var e = jQuery.Event( "keydown" );
$target.trigger(e);
});
I've tried using:
$target.keyup();
and as shown above:
var e = jQuery.Event( "keydown" );
$target.trigger(e);
I'm wondering if it's a problem with the order in which things load on the page.
I'd put your keyup code in a named function.
$(function () {
myFunction();
prodinput.on('keyup, keydown', function () {
myFunction();
})
};
var myFunction = function () {
var search = $('#prodinput').val().toLowerCase();
$('.support-product .browse-products a').each(function () {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
};
Assuming you don't need to support ancient browsers you can just listen for the input event which covers keypress and change events. Then after attaching the listener simply trigger the event:
$(function() {
$("#prodinput").on('input', function() {//alternatively you could use change and keyup
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}).trigger("input");//trigger the event now
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="prodinput" value="peanuts" />
<div class="support-product">
<ul class="browse-products">
<li>jam</li>
<li>elephants</li>
<li>peanuts</li>
</ul>
</div>

detect click on link in Firefox

I want to detect in my firefox extension if a link has been clicked. So far, for this I add a click event listener to the window
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
handleWindowClick : function(event) {
if ("event.target is a link") {
// do something
}
};
For some links the event.target is simple the URL. However, for some links I get, e.g., a HTMLSpanElement as event.target. Am I on the right track to catch link clicks or are there other ways? If it works this way, how can I ensure the successfully test if the event.targer is a link?
You're adding an event listener to the main window which registers any click. The url's you're having problems with must be wrapped in a <span> tag. What you need is event delegation
Why don't you just put the click event listener to anchors (<a>)?
var hrefs = document.getElementsByTagName('a');
for (i = 0; i < hrefs.length; i++) {
hrefs[i].addEventListener(...)
...
}
or in jQuery:
$('a').click(function () {
...
});
check this out, i hope this is what you are looking for.
window.addEventListener("click", function(event) {
handleWindowClick(event);
}, false);
function handleWindowClick(event){
var origEl = event.target || event.srcElement;
if(origEl.tagName === 'A')
alert("anchor link is clicked");
else if(origEl.parentNode.tagName === 'A')
alert("clicked inside anchor");
else if(origEl.tagName === 'SPAN')
alert("span is clicked");
}
fiddle : http://jsfiddle.net/5zXkN/3/
I extended the answer of dku.rajkumar to support arbitrary constructs within "A"-tags. I'm simply go up the tree until I either find an "A" or I'm at the root (so no link clicked in this case). It seems to do the trick. Thanks to all for your help!
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
isLink : function(element) {
if(element.tagName === 'A')
return true;
else
if (element.parentNode)
return this.isLink(element.parentNode)
else
return false;
},
handleWindowClick : function(event) {
var element = event.target || event.srcElement;
var isLink = this.isLink(element);
if (isLink)
dump("A link has been clicked.\n");
},

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources