I'm building a web application and am learning as I go.
This is the first question that I am posting.
I have created a series of SPAN elements ,that behave like buttons.
After I click an element (the Orange one), I want to effectively disable it by changing its class (and hence its colour to Grey).
Firebug before .on("click):
<span class="sample_but3 sample_butOrange">3</span>
Firebug after .on("click"):
<span class="sample_but3 sample_butGrey">3</span>
I can see, using firebug, that the class ".sample_butOrange" is removed and the class ".sample_butGrey" is added exactly as I expect.
But its the next bit that has got me stumped.
Now if I click the Grey button (which was originally Orange) I'm still get alerted that I pressed the Orange button, instead of being alerted that I pressed the Grey one.
NOTE: I have put in alerts that notify which button is pressed.
Can someone explain to me what is happening?
Here is the full code as an example:
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="sample_button.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
// Grey button means do nothing.
function sample_processGrey() {
alert("You pressed the grey button. Don't do anything as this button is disabled.");
}
function sample_processOrange() {
alert("You pressed the orange button");
$(".sample_but3").addClass("sample_butGrey").removeClass("sample_butOrange");
}
$(document).ready(function () {
// Do something when the buttons are pressed.
$(".sample_butGrey").on("click", sample_processGrey);
$(".sample_butOrange").on("click", sample_processOrange);
});
</script>
</head>
<body>
<span class="sample_but1 sample_butPurple">1</span>
<span class="sample_but2 sample_butGreen">2</span>
<span class="sample_but3 sample_butOrange">3</span>
<span class="sample_but4 sample_butRed">4</span>
<span class="sample_but5 sample_butBlue">5</span>
</body>
</html>
You can't attach events to elements that don't exist yet. But you can attach events to parent elements that do exist, and then look for the child target. jQuery makes this easy with event delegation. Here is an example:
$("body").on("click", ".sample_butGrey", sample_processGrey);
This tells jQuery to attach an event to the body tag, and to look for an element with the class sample_butGrey when clicked. If found call the sample_processGrey method. Here is a working example:
http://jsfiddle.net/AyQq8/4/
The onClick event is place on the JQuery element selected when the DOM is ready.
If you need to change the click event, you could add it to the target button in the same time to change the button class.
I hope it may help you to understand this issue.
Have a nice day
Check this
function sample_processGrey() {
alert("You pressed the grey button. Don't do anything as this button is disabled.");
}
function sample_processOrange() {
alert("You pressed the orange button");
$(".sample_but3").addClass("sample_butGrey").removeClass("sample_butOrange");
}
// Do something when the buttons are pressed.
$(".sample_butGrey").on("click", sample_processGrey);
$(".sample_butOrange").on("click", sample_processOrange);
DEMO
Have you tried using .hasClass() to determine the current class? Or have you tried fetching the class to determine what it is before choosing a dynamic response with elm.attr('class') ? You can also use .find() to find the new class added in the content of the container and re-select it again like: $('body').find('.sample_butGrey').on('click', function(){ /* New gray was clicked */ }) If it doesn't exist, clearly it's not there, so you can run a fail response or something else.
Related
Problem:
I'm trying to implement a dropdown form from a button. However, I'm having issues with the form not staying visible even after the condition is met. I'm new to javascript and css, so bear with me if it's a silly error. Thanks in advance.
What I want to do:
The form will be hidden by default.
When a user hovers over an image button, the form should be shown and hidden after the mouseleave.
If the user clicks the button, then the form should stay visible so that the user can enter the data and sumbit it.
Observation:
The objectives #1 and #2 from above are working as expected.
As opposed to objective #3, the form automatically hides even after the button click.
Unsuccessful Methods:
Using .show() instead of .css("display","block")
Using form:hover to set display:block.
Using setTimeout(hide_function,500) hides the form after 500ms regardless of the button click.
Code:
Here's the link to my jsfiddle that you can use to test it out.
References:
For button click detection.
For changing display property.
Just change data attr:
$('#dropbtn').click(function() {
$(this).data('clicked', 'yes');
$('#loginForm').css('display', 'block');
});
https://jsfiddle.net/d3h8gvek/3/#run //fixed result
i have modified your code little bit please check with the fiddle
$('#dropbtn').click(function() {
$(this).data('clicked', 'yes');
$('#loginForm').addClass('activate');
});
https://jsfiddle.net/d3h8gvek/7/
I've been working on trying to trigger an onchange listener with java script in Mozilla Firefox. I've found a lot on Stack Overflow posted about this, but nothing seems to be working for my unique case.
I've created this HTML with a onchange listener from an onchange event using this helpful post (JavaScript OnChange Listener position in HTML markup). Here's my code:
<HTML>
<head>
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementsByClassName('search-box')[0].addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
}
function loadXMLDoc(){
alert('It worked');
}
}
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
}
</script>
</head>
<BODY>
<input type="text" class="search-box" placeholder="Player Search">
<br \>
<button type="button" onclick="addTextCallListener()">Click Me!</button>
</BODY>
</HTML>
I also saved it as this jsfiddle (for some reason I had to keep it all together for it to work, I couldn't break it up into js and html).
https://jsfiddle.net/josephfedor42/crogL0zd/1/
If you play with this jsfiddle you can see that entering text and pressing enter will trigger the listener and the pop up with the message “It worked” will appear.
But if the button “Click Me!” is pressed it only changes the value of the text box, and the onchange listener is not called.
I realize I could easily add an onchange event to this button. But I want to to trigger the listener by programatically/ superficially using javascript in my addTextCallListener() function.
I've tried the simple stuff, like calling
searchBox.onchange();
searchBox.focus();
searchBox.click();
And a combination of these to add and remove the focus. But it doesn't seem to work. I've found quite a few posts on triggering an onchange event, but nothing that works in Firefox.
Any help would be appreciated.
Thanks for that link of a possible duplicated question. I had checked out that link before.
But I gave it a try again. I saved the jsfiddle from them both and neither one work.
My implementation of Dorian's answer
https://jsfiddle.net/josephfedor42/zaakd3dj/
My implementation of Alsciende's answer
https://jsfiddle.net/josephfedor42/xhs6L6u2/
emphasize mine
According to the mdn page about the change event,
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user.
and to whatwg specs :
When the input and change events apply (which is the case for all
input controls other than buttons and those with the type attribute in
the Hidden state), the events are fired to indicate that the user has
interacted with the control.
Therefore, setting the value of an input is not an action "committed by the user" nor a sign that "the user has interacted with the control", since it was made by the code.
So, even if the specifications for this event are kind of unclear, the event should not fire when you change its value by code.
Something like this should work:
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
//fire the event
if (document.createEvent) {
searchBox.dispatchEvent('change');
} else {
searchBox.fireEvent("onchange");
}
}
Here is the code I needed to add to my function addTextCallListener:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'change', true, true );
searchBox.dispatchEvent(evObj);
I updated the jsfiddle. The working code is here https://jsfiddle.net/josephfedor42/crogL0zd/7/
Replace onchange with change in this part:
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
I'm trying to show a textarea element when I click on an input element. The goal is to show the textarea, but when I click anywhere else, the textarea disappears.If I click anywhere on the textarea, it stays visible.
I saw a similar example of one on stackoverflow --> Link to similar question
The method was to add an addEventListener to the html tag by using document.documentElement, so basically the whole page, but I was wondering if there was an alternative? And is it safe to add an addEventListener to an entire page?
The code to addEventListener to entire page:
document.documentElement.addEventListener('click',clickhandler,false);
I'm not trying to be picky either, but I would like to avoid using a timeout on the element
Besides the code above, I first tried using the click event, and everything works fine, but when I click anywhere else the textarea doesn't disappear.
I then tried the focus/blur events, but when the input loses focus, the textarea disappears.
I was thinking of an if conditional for the click function... but I'm not sure how that would work without adding a click event to the entire page...
JSFiddle : http://jsfiddle.net/LghXS/
HTML\
<input type="text" id="email">
<textarea id="suggestion"></textarea>
CSS
textarea{
display:none;
}
JS
var textarea = document.getElementById('suggestion');
var input = document.getElementById('email');
// Using the Click Event
input.addEventListener('click',function(){
var display = textarea.style.display;
if(display === '' || display === 'none'){
textarea.style.display='inline-block';
}else{
textarea.style.display='none';
}
});
// Using the Focus and Blur
/*
input.addEventListener('focus',function(){
textarea.style.display='inline-block';
input.addEventListener('blur',function(){
textarea.style.display='none';
});
});
*/
Sooo, any ideas?
In my program an area called 'validDrop' is highlighted for the user to drag and drop items into.
A new area is highlighted when the button, 'minibutton' is clicked.
I want to tell the program to only allow the button to be clicked if the current area (validDrop) is styled by 'wordglow2' and 'wordglow4'.
I have tried this, Why won't it work?
if ($(validDrop).hasClass('wordglow2', 'wordglow4')) {
$('.minibutton').click(true);
} else {
$('.minibutton').click(false);
}
Because hasClass doesn't take more than one parameter, and because .click either triggers a click or binds a click listener, it doesn't set clickability.
Depending on what .minibutton is, you could do something like:
var valid = $(validDrop).hasClass('wordglow2') && $(validDrop).hasClass('wordglow4')
$('.minibutton').prop('disabled', !valid);
If it's not a type that can be disabled, you might consider something like this:
$('.minibutton').toggleClass('disabled', !valid);
And bind the click listener like so:
$(document).on('click', '.minibutton:not(.disabled)', function() {
// click action here
});
As ThiefMaster points out in comments, $(validDrop).is('.wordglow2.wordglow4') is a functionally equivalent way of checking that the drop has both classes.
You can alsou use .bind() and .unbind() to add and remove click event to your button as in my example http://jsfiddle.net/Uz6Ej/
my error message below, with a highlighted field is working perfectly. Except now the powers that be want a different functionality.
Currently the error messaging highlights the field with a red border, and on focus the border is removed. However, now the powers that be want the red highlighting to persist until the user hits submit onclick="return formSubmit()"
I've tried using a .submit function (removing the unbind and remove focus from the .focus function, but the red highlighting persists regardless.
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$(this).removeClass("CO_form_alert")
.parent().removeClass("alertRed"); // undo changes
$('.errorPopup').hide(); // hide error popup
});
}
Not sure I understand you. If not please tell me, but can't you just do:
$('.theform').submit(function() {
$('input', this).removeClass('CO_form_alert').parent().removeClass('alertRed');
$('.errorPopup').hide();
return false;
});
Why do you need to unbind?
I was so narrow minded in my looking for a solution above - trying to tie the removeClass with the form submit (which had to many actions tied into it and would have been overly complicated).
Instead, I just did a remove class at the beginning of the error checking:
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");