get and performing function + parameters from HTML5 data- element with jquery - javascript

I am making a phonegap program and I want to use a .on('tap') event instead of onClick="blah(param1,param2)" because of the 400ms delay. What I wanted to do was give a list of "tappable" items a class of "button1" and with each item give it a data-meth="dosomething3()" and then retrieve that when something is tapped. So far my example does not use tap but click instead.
<script>
$(document).ready(function() {
console.log('document ready');
$(".button1").on('click', function(e){ //this will changed to 'tap' eventually
e.preventDefault();
console.log("logged click");
var tempp=$(this).data("meth");
alert(tempp);
tempp; // thought this would call the function as it is written in the data-meth value but it doesn't
});
});
function dosomething(){
console.log('dosomething called');
}
function dosomething(var1,var2){
alert('hello:' +var1+' just showing var2'+var2);
}
</script>
My simple html is
<ul>
<li style="text-align:center" class="button1" data-meth="dosomething()" >One</li>
<li style="text-align:center" class="button1" data-meth="dosomething2(var1,var2)">Two</li>
<li style="text-align:center" class="button1" data-meth="dosomething3()">Three</li>
</ul>
How can i grab and call the function based or what is stored in the data-meth value?

Off the top of my head:
$(".button1").click(function() {
var functionName = $(this).attr("data-meth").split("(")[0];
var functionParams = $(this).attr("data-meth").split(")")[0].split[","];
window[functionName](functionParams);
});​
functionParams would be an array containing your values. That may or may not be what you need. You could also use the ever-evil eval like so:
$(".button1").click(function() {
eval($(this).attr("data-meth"));
});​
In which case you could pass in your parameters and treat them as usual.

Related

changing class name and sending parameter in javascript

I would like to change the class of a tag and send a parameter i to the myFunction the tag is without id or name:
<a class="active" onclick="myFunction('i')"></a>
<script>
function myFunction(obj) {
}
</script>
using this in the function like myFunction(this,'i') doesn't work.
using this in the function like myFunction(this,'i') doesn't work.
That should work, you just need to amend the function to accept the element as an argument.
However you should note that on* event attributes are massively outdated and should be avoided where possible. Use unobtrusive event handlers instead:
Array.from(document.querySelectorAll('a.active')).forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
console.log(this.dataset.foo);
});
});
One
Two
Three
Update:
You mentioned in the comments that you're going to use jQuery AJAX, so you can simplify above with jQuery:
$('a.active').click(function(e) {
e.preventDefault();
console.log($(this).data('foo'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
One
Two
Three
You can do something like this:
function myFunction(obj) {
var data = obj.attr("data-param");
obj.removeClass("active");
alert(data);
}
$(document).ready(function(){
$(".test").on("click", function(){
myFunction($(this))
});
});
<a class="test active" href="javascript:void(0);" data-param="i">test</a>
Fiddle:
https://jsfiddle.net/u81g6qk4/10/
You can pass a reference to an HTML element by putting this is the function. Then you can use the element reference to do stuff to it without needing a id or name attribute.
someOtherClass is an assumed variable that contains the name of the class you want to add. Change it to whatever class or variable you want to use.
<a class="active" onclick="myFunction(this, 'i')"></a>
<script>
function myFunction(obj, param2) {
$(obj).removeClass("active");
$(obj).addClass(someOtherClass);
}
</script>
Use this if you do not want to use Jquery
<a class="active" onclick="myFunction(this, 'i')">Click Me</a>
<script>
function myFunction(element, str) {
console.log(str);
element.setAttribute('class', 'clicked');
}
</script>

Increment a variable from jQuery .click

So, I'm trying to make a game where basically you click the picture, it disappears, and then 1 is added to a javascript variable.
So, I have this:
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
and I have some pictures and when you click on them, they disappear. For example:
<center><p><img src="test.jpg" border="0"></p></center>
I just want it so that the code below, as you can see above, adds 1 to a javascript variable called picturesRemoved
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
Define the variable (as a global most likely)
var picturesRemoved = 0;
Then increment inside your handler:
picturesRemoved++;
Overall:
$(document).ready(function(){
var picturesRemoved = 0;
$("p").click(function(){
$(this).hide();
picturesRemoved++;
});
});
Given HTML like this:
<div>
Show Count
<ul>
<li>
<img src="test.jpg" border="0">
</li>
<li>
<img src="test.jpg" border="0">
</li>
</ul>
</div>
You could use the following to do what you are trying to accomplish:
$(document).ready(function(){
var picturesRemoved = 0;
$('li').click(function(){
$(this).hide();
picturesRemoved++;
});
$('.showCount').click( function(e){
e.preventDefault();
alert(picturesRemoved);
});
});
var picturesRemoved = 0; sets a default value to the variable and initializes it.
picturesRemoved++; will increment the value as an item is selected.
I also included a link and click handler that will show you the current value of the variable as an example of how you could use it in you JS later on.
e.preventDefault(); will prevent the default action of the anchor. Otherwise the anchor will behave based on the set HREF value.
alert(picturesRemoved); uses the standard JS alert function to show the variable.

Defining a single jQuery function for separate DOM elements

I have several jQuery click functions- each is attached to a different DOM element, and does slightly different things...
One, for example, opens and closes a dictionary, and changes the text...
$(".dictionaryFlip").click(function(){
var link = $(this);
$(".dictionaryHolder").slideToggle('fast', function() {
if ($(this).is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
});
HTML
<div class="dictionaryHolder">
<div id="dictionaryHeading">
<span class="dictionaryTitle">中 文 词 典</span>
<span class="dictionaryHeadings">Dialog</span>
<span class="dictionaryHeadings">Word Bank</span>
</div>
</div>
<p class="dictionaryFlip">toggle dictionary: off</p>
I have a separate click function for each thing I'd like to do...
Is there a way to define one click function and assign it to different DOM elements? Then maybe use if else logic to change up what's done inside the function?
Thanks!
Clarification:
I have a click function to 1) Turn on and off the dictionary, 2) Turn on and off the menu, 3) Turn on and off the minimap... etc... Just wanted to cut down on code by combining all of these into a single click function
You can of course define a single function and use it on multiple HTML elements. It's a common pattern and should be utilized if at all possible!
var onclick = function(event) {
var $elem = $(this);
alert("Clicked!");
};
$("a").click(onclick);
$(".b").click(onclick);
$("#c").click(onclick);
// jQuery can select multiple elements in one selector
$("a, .b, #c").click(onclick);
You can also store contextual information on the element using the data- custom attribute. jQuery has a nice .data function (it's simply a prefixed proxy for .attr) that allows you to easily set and retrieve keys and values on an element. Say we have a list of people, for example:
<section>
<div class="user" data-id="124124">
<h1>John Smith</h1>
<h3>Cupertino, San Franciso</h3>
</div>
</section>
Now we register a click handler on the .user class and get the id on the user:
var onclick = function(event) {
var $this = $(this), //Always good to cache your jQuery elements (if you use them more than once)
id = $this.data("id");
alert("User ID: " + id);
};
$(".user").click(onclick);
Here's a simple pattern
function a(elem){
var link = $(elem);
$(".dictionaryHolder").slideToggle('fast', function() {
if (link.is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
}
$(".dictionaryFlip").click(function(){a(this);});
$(".anotherElement").click(function(){a(this);});
Well, you could do something like:
var f = function() {
var $this = $(this);
if($this.hasClass('A')) { /* do something */ }
if($this.hasClass('B')) { /* do something else */ }
}
$('.selector').click(f);
and so inside the f function you check what was class of clicked element
and depending on that do what u wish
For better performance, you can assign only one event listener to your page. Then, use event.target to know which part was clicked and what to do.
I would put each action in a separate function, to keep code readable.
I would also recommend using a unique Id per clickable item you need.
$("body").click(function(event) {
switch(event.target.id) {
// call suitable action according to the id of clicked element
case 'dictionaryFlip':
flipDictionnary()
break;
case 'menuToggle':
toggleMenu()
break;
// other actions go here
}
});
function flipDictionnary() {
// code here
}
function toggleMenu() {
// code here
}
cf. Event Delegation with jQuery http://www.sitepoint.com/event-delegation-with-jquery/

How to write this Javascript code to show/hide for each personal elements?

How can I write this code in a loop?
Actually I am using some different links to show and hide box for each related link. I want to show/hide box for each link showing information related to that link.
function hidedetailbox1()
{document.getElementById("plc1").style.display="none";}
function showdetailbox1()
{document.getElementById("plc1").style.display="block";}
function hidedetailbox2()
{ document.getElementById("plc2").style.display="none";}
function showdetailbox2()
{document.getElementById("plc2").style.display="block"; }
function hidedetailbox3()
{document.getElementById("plc3").style.display="none";}
function showdetailbox3()
{document.getElementById("plc3").style.display="block"; }
function hidedetailbox4()
{document.getElementById("plc4").style.display="none";}
function showdetailbox4()
{document.getElementById("plc4").style.display="block";}
function hidedetailbox5()
{document.getElementById("plc5").style.display="none";}
function showdetailbox5()
{document.getElementById("plc5").style.display="block";}
function hidedetailbox6()
{document.getElementById("plc6").style.display="none";}
function showdetailbox6()
{document.getElementById("plc6").style.display="block";}
function hidedetailbox7()
{document.getElementById("plc7").style.display="none";}
function showdetailbox7()
{document.getElementById("plc7").style.display="block";}
function hidedetailbox8()
{document.getElementById("plc8").style.display="none";}
function showdetailbox8()
{document.getElementById("plc8").style.display="block";}
function hidedetailbox9()
{document.getElementById("plc9").style.display="none";}
function showdetailbox9()
{document.getElementById("plc9").style.display="block";}
function hidedetailbox10()
{document.getElementById("plc10").style.display="none";}
function showdetailbox10()
{document.getElementById("plc10").style.display="block";}
function hidedetailbox11()
{document.getElementById("plc11").style.display="none";}
function showdetailbox11()
{document.getElementById("plc11").style.display="block";}
function hidedetailbox12()
{document.getElementById("plc12").style.display="none";}
function showdetailbox12()
{document.getElementById("plc12").style.display="block";}
function hidedetailbox13()
{document.getElementById("plc13").style.display="none";}
function showdetailbox13()
{document.getElementById("plc13").style.display="block";}
You could use a function like this...
var toggleDisplay = function(i, hide) {
document.getElementById('plc' + i).style.display = hide ? 'none' : '';
}
You pass it the number (as i) and whether it should hide or reset (as hide) the display property.
function hidedetailbox(id){
....
Suppose you have 10 comments listed in the page,
when you display it from the server, in your server script keep a count like
<div id="1">comment1</div>
<div id="2">comment2</div>
<div id="3">comment3</div>
etc...
if it's any other content like a image, you can use
<...name="1"....>
now you can handle them in a loop like this,
for(i++){
getElementById(i); //handle it the way you want here.
}
further if you have a specific name for the element, you can concat with the "i"
like
getElementById("comment"+i);
Suggestion: you can use jquery to do this for you
.toggle() .show() .hide() can be a good thing to look at..
Good luck :)
Since you mentioned jquery. You can use toggle
$('.boxlink').click(function(e) {
$($(e.target).attr('href')).toggle();
return false;
});
Your links in HTML will look something like this:
Toggle PLC 1
Toggle PLC 2
toggle example:
<html>
<head>
<script type="text/javascript">
var toggleDisplay = function(id) {
if (document.getElementById(id).style.display == 'none'){
document.getElementById(id).style.display = '';
}
else {
document.getElementById(id).style.display = 'none';
}
}
</script>
</head>
<body>
<table>
<tr><td onmouseover="toggleDisplay(1);">Test toggle</td><td id=1 name=1 >Toggle me!</td></tr>
</table>
</body>
</html>

passing a parameter with onclick function is read as a variable when it should be read as a string

Here is my issue:
I am creating dynamically a button with an onclick function like this:
$("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');
The parameters are well read but the function is not trigger, and I've got this error message:
"bob is not defined" when bob is the string value of the param1.
Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.
Thanks much for your help!
That's because this string right here:
'onclick="remove('+param1+','+param2+');"'
Will look like this in the end:
'onclick="remove(foo, bar);"'
You probably want it to look like this:
'onclick="remove(\'foo\', \'bar\');"'
So change it to this:
'onclick="remove(\''+param1+'\', \''+param2+'\');"'
You could also do this:
$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
remove(param1, param2);
});
Edit: I also noticed that you were missing one " from your $()-call: $("#test) should be $("#test").
I can suggest you this
<script type="text/javascript">
//<![CDATA[
var i = 0;
$(function () {
$("#lnkAdder").click(function () {
// appending new item
$("#Container").append(
$("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
var data = ++i;
alert("I'm clicked, I'm number " + data);
})
);
});
});
//]]>
</script>
Add item
<div id="Container"></div>
The key here is the javascript closure.
As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.

Categories