Not able to get into the functions for onclick & onmouseout/over events in Chrome and Firefox. Any reasons for not working in Chrome and FF is there a way around for this. These work fine in IE9 and Opera..
Code in html page is shown below:
<script language="JavaScript" for="SmartGridCell" event="onclick()">
sg_CellClick(event.srcElement);
</script>
<script language="JavaScript" for="SmartGridCell" event="onmouseover()">
sg_MouseOverCell(event.srcElement);
</script>
more click events...
<script language="javascript" for="optSet" event="onclick()">
mc_SelectAnElement(this, document.getElementsByName('optSet'));
</script>
<script language="javascript" for="answerChoice" event="onclick()">
mc_SelectAnElement(this, document.getElementsByName('answerChoice'));
</script>
This is what I have done so far, but I cannot get the fire the event in Chrome...
<script language="JavaScript">
var s1=document.getElementsByName('optSet');
for (var i=0;i<s1.length;i++)
{
s1[i].addEventListener("click",mc_SelectAnElement(this, document.getElementsByName('answerChoice')),false);
}
</script>
Tried this as well, this snippet gets me to the function but the values selected never persists...
if (document.addEventListener)
{
document.addEventListener("click",function (e){
var srcElement= e.target;
var tagName= srcElement.tagName;
if(tagName="optSet")
{
mc_SelectAnElement(srcElement, document.getElementsByName('optSet'));
}
//mc_SelectAnElement(this, document.getElementsByName('optSet'));
},true);
}
Thanks-
In modern JavaScript it would be something like:
if (document.addEventListener) {
document.addEventListener('click', function (e) {
var el = e.target;
var id = el.id;
// the "for" attribute refers to an ID
if (id == 'SmartGridCell' || id == 'SmartGridHeaderCell') {
sg_CellClick(el);
}
}, true);
/* repeat the same for "mouseover" and "mouseout" */
}
You can leave the old script too, they won't clash.
Why this works in IE – because they invented their own ugly KnockoutJS 20 years ago. And it's non-standard of course (DOM 2 says Reserved for future use for the for and event attributes).
Related
$('.submit__form').on('click', function(e) {
e.preventDefault();
var id = '.' + $(this).data('id');
var person__name = $('#person__name').val();
var person__email = $('#person__email').val();
var booking__participants = $('#booking__participants').val();
alert(person__email || 'none');
// if (person__email === '' || person__name === '' || booking__participants === '') {
// alert('Preencha os campos obrigatórios.');
// } else {
// $(id).submit();
// }
});
I don't know why, but i can't pick the value of the person__name and person__email, the most strange part is that i can pick the value in the console on the browser... someone knows what could be causing this?
This is not a problem of html the 2 inputs fields have the id person__name and person__email.
The code is in a external file, and i am calling that in the bottom of my html.
HTML:
<form>
<input id="person__name" name="person.name" type="text" />
<input id="person__email" name="person.email" type="email" />
<a class="submit__form">Submit</a>
</form>
I cant use the submit input.
UPDATE:
The scripts in the bottom of the page:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/headroom/0.6.0/headroom.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.5/waypoints.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.1.0/velocity.min.js"></script>
<script src="//cdn.jsdelivr.net/velocity/1.1.0/velocity.ui.min.js"></script>
<script src="/client/scripts/main.js"></script>
Inside the main script:
(function() {
//code
})();
If you want to alert the name, make sure you use the name in the jQuery
alert(person__name || 'none');
// Not:
alert(person__email || 'none');
http://jsfiddle.net/376fLujs/3/
Also, make sure your script is included properly. Include the jQuery before your script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="local.js" type="text/javascript"></script>
add: console.log("working"); as the very first line of your script
open the chrome console / Firebug and refresh your page.
if you don't see "working" in the console, your javascript is not included properly.
Edit: based on your comments again. If you have multiple forms, re-using the same ID, it will not work. Always keep IDs unique. Since your link is inside of the form like your input, you could do this:
var person__email = $(this).parent().find("input[name='person.email']").val();
// DRX points out that escaping may be necessary:
var person__name = $(this).parent().find("input[name='person\\.name']").val();
http://jsfiddle.net/376fLujs/4/
I would say try using this for your event handling:
$(document).on('click', '.submit__form', function(e) {
//code here
});
The reason it might not be working is because the element might not yet be created when the script loads. This should take care of that issue.
is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id + " and " + event.target.class);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
click me 1
click me 2
</body>
</html>
jsfiddle code here
Try:
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id+" and "+$(event.target).attr('class'));
});
});
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
You will get all the class in below array
event.target.classList
A variant on Vishesh answer, which instead returns a Boolean:
event.target.classList.contains(className)
$(document).ready(function() {
$("a").click(function(event) {
var myClass = $(this).attr("class");
var myId = $(this).attr('id');
alert(myClass + " " + myId);
});
})
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
click me 1
click me 2
</body>
</html>
This works for me. There is no event.target.class function in jQuery.
If you are using jQuery 1.7:
alert($(this).prop("class"));
or:
alert($(event.target).prop("class"));
Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like
var t = ev.srcElement || ev.target;
thus leading to
$(document).ready(function() {
$("a").click(function(ev) {
// get target depending on what API's in use
var t = ev.srcElement || ev.target;
alert(t.id+" and "+$(t).attr('class'));
});
});
Thx for the nice answers!
$(e.target).hasClass('active')
HTML
<!doctype html>
<html>
<head>
</head>
<body>
<button id="b1" type="button">Show Spoiler</button>
<p id="p1" style="display:none"> This is a damn paragraph.</p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JS
function bindEvent(element, eventName, eventHandler) {
var el = $(element)[0];
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false)
} else if (el.attachEvent) {
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent('#b1', 'click', function() {
$('#p1').toggle('blind');
if ($('#b1').text() == 'Show Spoiler') {
$('#b1').text('Hide Spoiler');
} else if ($('#b1').text() == 'Hide Spoiler') {
$('#b1').text('Show Spoiler');
}
});
I'm new to jQuery and Javascript so I made this simple script to show and hide a paragraph and to change the button texts whenever clicked. My problem is that this seems a bit clunky. Is there a better, shorter, and simpler way to achieve the same result?
First of all, jQuery already normalizes DOM event listeners for you across browsers, so your bindEvent function isn't necessary anymore. Here's the short way, using some stuff you can look up yourself in the jQuery API, to do what you're doing.
var $b1 = $('#b1')
, $p1 = $('#p1')
, hideText = 'Hide Spoiler'
, showText = 'Show Spoiler'
$b1.on('click',function() {
var text = $b1.text()
, newText = text === showText ? hideText : showText
$p1.toggle('blind')
$b1.text(newText)
})
Here are a few things to notice:
Your example function assumes a single spoiler #p1 and a single reveal button #b1. In production, this will probably be based on classes, like .spoiler and .spoiler-trigger, and there will be multiple spoilers on a page. In that case, you'll need to get the value of this. In this example let's assume that the reveal button is always a sibling of the spoiler itself.
$('.spoiler-trigger').on('click',function() {
var $this = $(this)
, $thisSpoiler = $this.siblings('.spoiler').eq(0)
, text = $this.text()
, newText = text === showText ? hideText : showText
$thisSpoiler.toggle('blind')
$this.text(newText)
})
The jQuery .on method is the cross-browser event listener function that you'll want to start using.
jQuery selectors we use repeatedly, like $(this) or $('#b1'), should be cached in local variables for performance.
I'm using a ternary conditional instead of an if statement to determine what the show/hide text should be, because in this very simple case I consider it more readable.
You can make this work with simple 3 lines of code using awesome jquery. trigger the button click event, and on click -> toggle the element 'P'. This should help : working demo
$("#b1").click(function () {
$("#p1").toggle('slow');
});
I have a form that has many select menus, most of them are Yes/No and depending on the selected option, I display/hide some advanced options. One of the select menus is the following:
<td><%= f.select :CBIAvailable, ['Yes' , 'No'],{}, {:id=>"cbi_available_id", :class=>"cbi_available_class", :onChange=>"showHideOptions('cbi_available_id','cbi_options_id')", :onLoad=>"showHideOptions('cbi_available_id','cbi_options_id')"} %></td>
When I change from 'Yes' to 'No' or the opposite, showHideOptions javascript functions is called properly, but I can't have that function to be called when I reload the form.
Anyone can tell me what am I dong wrong?
Thanks
UPDATE
<script language="javascript" type="text/javascript">
function showHideOptions(selectorId,optionsId) {
if (document.getElementById) {
var selector = document.getElementById(selectorId);
var options = document.getElementById(optionsId);
if (selector.value == 'Yes') {
options.style.display = 'block';
return false;
} else {
options.style.display = 'none';
return false;
}
}
window.onLoad = showHideOptions('cbi_available_id','cbi_options_id');
function yourFunction(){
//get that select element and evaluate value
//do you change stuff here
}
window.onload = yourFunction; //this gets fired on load
//"select" is your element,
//fetched by methods like document.getElementById();
select.onchange = yourFunction; //this gets fired on change
//you can also use attachEvent (IE) or addEventListener (Others)
here's a working demo:
<select id="testSelect">
<option value="yes">YES</option>
<option value="no">NO</option>
</select>
function getOption() {
alert('foo');
}
var select = document.getElementById('testSelect');
select.onchange = getOption;
window.onload = getOption;
This could happen when you receive postback from your remote server and your response doesn't have <script type="javascript">... yourfunction()...</script>.
Each time you get new response you should send script and exacute it or append to your html element approciate event handler.
Another solution is to use jQuery and use .live() event. This event attach dynamically behaviour to your html. I strongly recommend you to use jQuery with live because this library is one of most used libraries in production environment.
Edit
<script type="text/javascript" src="path_to_jquery.js"></script>
<script type="text/javascript">
function showHideOptions(id1,id2){
//Your code
}
$(document).ready(function() {
//This function waits for DOM load
//execute your function for first time
showHideOptions('cbi_available_id','cbi_options_id');
//This selector you have to modify or show us generated html to
// choose the best selector for this purpose
$('.cbi_available_class').live('change',function(){
//This will fire change event of html class="cbi_available_class"
showHideOptions('cbi_available_id','cbi_options_id');
});
});
</script>
Is there a jQuery plugin or JavaScript script that automagically loops through each CSS hover (found in an external stylesheet) and binds it with a double touchdown event?
Touchdown 1 - CSS :hover is triggered
Touchdown 2 - Click (link following or form action)
If there isn't something like this yet, can it be made and how (guidelines)?
EDIT:
To be clear, I am not in search of a double tap. Touchdown 1 is a single tab just like Touchdown 2 is. There can be as less as 0 seconds between both or as much as 3 minutes, that's the user's choice.
No touch:
:hover -> element becomes visible
click -> following link or other action
Touch (iOS):
touchdown 1 -> element becomes visible
touchdown 2 -> following link or other action
Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>iPad Experiment</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
if(navigator.platform == "iPad") {
$("a").each(function() { // have to use an `each` here - either a jQuery `each` or a `for(...)` loop
var onClick; // this will be a function
var firstClick = function() {
onClick = secondClick;
return false;
};
var secondClick = function() {
onClick = firstClick;
return true;
};
onClick = firstClick;
$(this).click(function() {
return onClick();
});
});
}
});
</script>
<style type="text/css">
a:hover {
color:white;
background:#FF00FF;
}
</style>
<body>
Google
stackoverflow.com
</body>
</html>
... or check out the demo on my web site. Note that it's set up to only work its magic on the iPad - detecting all versions of the iOS is another question in my books ;)
It works on the basis of the fact that...
After you click a link on the iphone or ipad, it leaves a simulated mouse hover that triggers the a:hover css styling on that link. If the link has a javascript handler that keeps you on same page, the hover state will not change until you click on another link.
Citation: Safari iphone/ipad “mouse hover” on new link after prior one is replaced with javascript
I've used this:
$(document).ready(function() {
$('.hover').bind('touchstart touchend', function(e) {
e.preventDefault();
$(this).toggleClass('hover_effect');
});
});
Before, to allow hover on certain elements. Obviously you'll need to tweak it for your own use, but it's a nice way to allow a touch and hold hover effect.
Here is a further optimized version that also handles closing the :hover
You'll have to encapsulate your site with a
<div id="container"></div>
for it to work. Just putting the closing event on the body did nothing
var bodyBound = false;
var container;
if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i))
{
container = $("#container");
// Provoke iOS :hover event
$("a.someLink").on("mouseover", handleHoverClick);
}
function handleClose(event)
{
container.off("click", handleClose);
bodyBound = false;
}
function handleHoverClick(event)
{
if (!bodyBound)
{
bodyBound = true;
// Somehow, just calling this function—even if empty—closes the :hover
container.on("click", handleClose);
}
}
I created this update apon Richard JP Le Guens solution. It works GREAT, but my version fixes the issue recognized by DADU.
Also I fixed his workaround to detect iPads. My solution detects any other touch devices too (except IE10 on MS surface, I didn't remember the MS special treatment).
My fix is not a 100% perfect solution, but it resets the hover fix at least when hovering another link.
<!DOCTYPE html>
<html>
<head>
<title>TouchDevice Experiment</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
if(document.createEvent("TouchEvent")) { // using document.createEvent is more reliable than navigator (Modernizr uses this practice)
$("a").each(function() { // have to use an `each` here - either a jQuery `each` or a `for(...)` loop
var onClick; // this will be a function
var firstClick = function() {
$("a").trigger("JWUnhover"); // triggering hoverfix reset if any link gets touched
onClick = secondClick;
return false;
};
secondClick = function() {
onClick = firstClick;
return true;
};
onClick = firstClick;
$(this).click(function() {
return onClick();
});
$(this).bind('JWUnhover', function(){ onClick = firstClick; });
});
}
});
</script>
<style type="text/css">
a:hover {
color:white;
background:#FF00FF;
}
</style>
</head>
<body>
Google
stackoverflow.com
</body>
</html>
There is no jQuery plugin that I know of to do such a thing.
You cannot trigger a css psuedo class such as ":hover". You can however loop through the anchor elements and add a css class ".hover" on touchstart and touchend events as follows:
var pageLinks = document.getElementsByTagName('a');
for(var i = 0; i < pageLinks.length; i++){
pageLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
pageLinks[i].addEventListener('touchend', function(){this.className = "";}, false);
}
To add a double finger tap gesture recognizer, you can use a plugin such as:
http://plugins.jquery.com/project/multiswipe
This worked for me!
// Ipad Navigation Hover Support
$('#header .nav li a').bind('touchstart touchend', function(e) {
if( $(this).attr("href") != "" ){
window.location = $(this).attr("href");
}
});
Here's an optimized version of the jQuery code provided by Richard JP Le Guen:
$(document).ready(function() {
$('a').each(function() {
var clicked = false;
$(this).bind('click', function() {
if(!clicked) return !(clicked = true);
});
});
});
There is a more simpler way to fix the issue with iOS and hover states, using CSS. For the link you have an issue with set the cursor property to pointer and the hover state will be ignored on iOS. For all links to function as expected, see below:
a
{cursor: pointer;}