Making array for click function in javascript - javascript

in my web i have many button that javascript for managing click function. Every button click has class for initial each of them. here the code
<script type="text/javascript">
$(document).ready(function(){
$(".data1").click(function(){
$("#line").val("1");
$("#pkategori").val("-Kategori Produk-");
$("#pname").val("-Nama Produk-");
$("#pnumber").val("");
$("#seri").val("");
$("#quantity").val("");
$("#ok").hide();
$("#cancel").hide();
$("#tnposisi").hide();
$("#nposisi").hide();
$("#tketp").hide();
$("#ketp").hide();
$("#tpjumlah").hide();
$("#pjumlah").hide();
$("#editsave").hide();
$("#editcancel").hide();
$("#input").hide();
$("#loading").hide();
$("#status").html("");
});
});
for my current web, i make this one by one until $(".data160").click(function(). it will be long code and not effective. My problem, How tomake this a simple code?

Give all the buttons the same class, and use data attributes for the different features.
<button class="data" data-line="1" data-kategory="-Kategori Produk-" data-name="-Nama Produk-">
Then write:
$(".data").click(function(){
$("#line").val($(this).data("line"));
$("#pkategori").val($(this).data("kategori"));
$("#pname").val($(this).data("name"));
$("#pnumber,#seri,#quantity").val("");
$("#ok,#cancel,#tnposisi,#nposisi,#tketp,#ketp,#tpjumlah,#pjumlah,#editsave,#editcancel,#input,#loading").hide();
$("#status").html("");
});
To handle them all at once.

separate it with several functions:
1、val and html together
2、hide together, you can create a function like this
function hideEl(el){
$('#'+el).hide();
}
var arrEls = ['pname','apple','msn'...];
$(arrEls).each(function(key,value){
hideEl(value);
});

Related

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

Animate.css shake effect not working every time

I'm making a Twitch Streamer application, that pulls some data using Twitch API, for a predetermined set of streamers.
I have three buttons to select all/online/offline channels, and I am looking to add the animated shake effect to all these buttons.
On my first attempt, I had a simple if/else check in place to make the shake work correctly - detect if the animated shake class already exists, if so, remove it, and then add it again. Else, just add it.
That didn't work. I found an answer here on SO that said it won't work that way because the addClass and removeClass occur so fast that the DOM doesn't have time to catch up.
I then used a queue with an anonymous function to add the class back after inducing a slight delay after the removeClass -
if ($(this).hasClass("animated shake")) {
$(this).removeClass("animated shake").delay(50).queue(
function() {
$(this).addClass("animated shake");
});
//$(this).addClass("animated shake");
} else {
$(this).addClass("animated shake");
}
Now, the shake effect works like 90% of the time, but if you keep switching back and forth between online/offline channels, there will be cases in between where the shake doesn't work.
Here's the app on Codepen.
I'd appreciate any help as to why it doesn't work every single time.
Note - The shake effect is on the online/offline buttons only, for now.
This works everytime :-D
function shakeButton($button) {
console.log('Shaking button')
$button.removeClass("animated shake");
setTimeout(
function() {
$button.addClass("animated shake");
},
25
);
}
$('button').click(function() {
shakeButton($(this));
});
<!-- Never mind, Just some Dummy html... -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Never mind this, Just some Dummy Results</h4>
<h3>Check out the JS instead</h3>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
I just used setTimeout instead .delay() And it worked a treat :-)
Good Job, Your code is nice and well documented :-D A Few things though...
In your code... you repeat the same code at three places, Instead you can create a function with that code and call that function everywhere instead ;-) This will make debugging easier.
The if statement you use is not necessary... Just remove animate and shake classes every time ( it won't throw any error ;-) ) and add them after some time again, this will make code simpler.
This code is implemented in this snippet...
http://codepen.io/shramee/pen/EyZJjN
can you try something like this?
$('.btn').on('click', function()
{
// Siblings will target other buttons but not the current one
$(this).addClass('animated shake').siblings().removeClass('animated shake');
});
[EDIT] more relevent to your structure:
According to your example structure you can add a class to your buttons wrapper like .btnWrapper for convenience and do:
$('.btn').on('click', function()
{
var clicked = $(this);
clicked.addClass('animated shake').parents('.btnWrapper').siblings().find('.shake').removeClass('animated shake');
})

How to set ButtonState Loading in HTML5 CSHTML Page

Here is my HTML entry that fires the GenerateBill() Javascript at the moment :
<a class="btn btn-primary" id="loading-example-btn" data-loading-text="Loading..." onclick="GenerateBill()">Generate Bill</a>
Here is the GenerateBill() method, this all works fine, all I want to do is add the button state feedback
function GenerateBill() {
var url = '/PremiseProvider/GenerateBill';
var data = {
StartDate: $('#from').val(),
EndDate: $('#to').val(),
premiseProviderId: $('#PremiseProviderId').val()
};
$("body").load(url, data);
};
Here is a code snippet from the Bootstrap 3 official Site on how to implement the button state feedback:
<script>
$('#loading-example-btn').click(function () {
var btn = $(this)
btn.button('loading')
$.ajax(...).always(function () {
btn.button('reset')
});
});
</script>
My Question is how can I implement in my GenerateBill script, the bootstrap example uses an Ajax call, can I make it work without making too many changes to what I have?
If I might make a few suggestions that will both fix your issue and improve your code.
Instead of using an onclick event, add an event listener in your javascript, and call the function from there.
Add the .button('loading') call to that same event listener.
Don't leave off the href for an <a> tag. It will cause some browsers to not show the pointer correctly on hover.
Your link will look as follows:
Generate Bill
Leaving your GenerateBill() logic alone, the listener you need to add to your javascript:
$('#loading-example-btn').click(function () {
$(this).button('loading');
GenerateBill();
});
A working example of this code (with GenerateBill() simplified) is available here: http://www.bootply.com/VTSNA1XMcm

Using Document Ready on Click Event

I am still new to javascript.
I have an application that has two buttons on the page. One is a cpu_vs_player button that displays one game and the other is a player_vs_player button that displays a different game. The problem is that all the code is located in one application.js file. There is no need to load the player_vs_player on $(document).ready(function(){}); if I were to play cpu_vs_player.
Any ideas on how I can get them to load only if I chose that game? (I am only using one route with all the information being hidden / shown based on the click).
The document.ready is nothing more than the moment after the page has rendered and the document needs to be populated with event listeners. Frankly there are multiple way of skinning this cat.
You can either do the jQuery way where you keep javascript and HTML divided:
<button id="button1">cpu_vs_player</button>
<button id="button2">player_vs_player</button>
And for JavaScript:
Assuming you have a function for each gameplay:
function cpu_vs_player() {
// start the game
}
function player_vs_player() {
// need another player
}
Add event listeners the jQuery way:
$(document).ready(function() {
$("#button1").click(function() {
cpu_vs_player();
});
$("#button1").click(function() {
player_vs_player();
});
});
OR you could use the method #Techstone shows you, though you could do it more direct. It all works though.
<button onclick="javascript:cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:player_vs_player();">player_vs_player</button>
Adding another option you can apply
In Javascript:
var Main = {
cpu_vs_player: function() {
alert("start cpu_vs_player");
},
player_vs_player: function() {
alert("start player_vs_player");
}
}
In your HTML:
<button onclick="javascript:Main.cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:Main.player_vs_player();">player_vs_player</button>
And yes, there is more ... ;-)
image that your two button and js definition like below
function LetsRock(Playmate) {
....
}
<input type='button' value='cpu_vs_player' id='cpu_vs_player' onclick='javascript:LetsRock(this.id);' />
<input type='button' value='player_vs_player' id='player_vs_player' onclick='javascript:LetsRock(this.id);' />
Try to use the function with parameters (i.e. 0 to cpu v/s player, 1 to player v/s player), and send from the menu page to the $(document).ready(function(){});

how can I intercept a click for all img's ? I have a bunch of images, each needs to reply to a click.

I would like to present images to my users, where they can select them. I need them to select a limited number, say 5, so:
The images are shown in a matrix, and the user can click them.
I thought:
function boom()
{
this.css('background-color','#fff');
this.data('clicked','yes');
// I should also make checks here to see how many were clicked already
}
$('img').click(boom);
// I thought this would connect all img's that were clicked upon to this function, where I can call the 'this' with the css function...
But it doesn't work as I thought it would...
Any help would do, thanks !
$(function(){
var clicked_img = 0;
$('img').click(function(){
$(this).css('background-color','#fff').data('clicked','yes');
clicked_img++;
});
});
EDIT: UPDATED CODE BELOW FOR NEW REQUEST, FOUND IN COMMENT THREAD:
Per your updated code request, if your HTML is this:
<img id="one" class="clicked" src="img/one.png" />
<img id="two" class="clicked" src="img/two.png" />
This JQuery has been fixed to work for you:
$('img.clicked').click(function(){
boom(this);
});
function boom(e) {
if($(e).data('clicked')=='yes') {
$(e).data('clicked','no').css('border','none');
}
else {
$(e).data('clicked','yes').css('border','3px solid #cccccc');
}
}
Working demo of the new code: http://jsfiddle.net/Vwye8/
Try assigning a variable to an annonymous function
var boom = function()
{
this.css('background-color','#fff');
this.data('clicked','yes');
// I should also make checks here to see how many were clicked already
}
and then calling the $('img').live("click",boom);
js fiddle here: http://jsfiddle.net/t7u6t/

Categories