combining multiple javascript var into one function - javascript

I know absolutely nothing about js but I stumbled on this and was wondering if someone could help me combine these two into one. I will probably end up having about 30 of them. is it possible for all 30 vars to be combined? each customPush will push a new html.
Thank you.
var customPush1 = function (event) {
myNavigator.pushPage('pageNav2.html', { data: { cardTitle:
event.target.textContent } })
};
var customPush2 = function (event) {
myNavigator.pushPage('pageNav3.html', { data: { cardTitle: event.target.textContent } })
};

yes. the plan is to have 30 buttons loading a separate html each
In this case, I'd do it a different way, rather than creating lots of functions, I would add some data-attributes to the buttons, and use delegated events.
But if you want to make it so that you can share code between functions. You can create a function that returns a function, and use closures to pass parameters. Below is an example.
function makePush(url) {
return function (event) {
myNavigator.pushPage(url, { data: { cardTitle:
event.target.textContent } })
}
}
var
customPush1 = makePush('pageNav2.html'),
customPush2 = makePush('pageNav3.html');
And here is an example of using delegated events on the buttons. It's uses jQuery as I find it quick and easy, but the same can be done without jQuery.
$('body').on('click', '[data-custom-push]', function () {
var page = $(this).attr('data-custom-push');
alert('Page = ' + page);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-custom-push="pageNav1.html">Button 1</button> <br>
<button data-custom-push="pageNav2.html">Button 2</button> <br>
<button data-custom-push="pageNav3.html">Button 3</button> <br>
<button data-custom-push="pageNav4.html">Button 4</button> <br>
<button data-custom-push="pageNav5.html">Button 5</button> <br>
<button data-custom-push="xyz.html">Button 6</button> <br>
<button data-custom-push="abc.html">Button 7</button> <br>

Related

Pass in function parameter without invoking function

document.querySelector(DOM.refreshRem).addEventListener('click', function(param));
This is the line I'm having trouble with, I want to connect the function but without the (), so it isn't invoked right away, but the function accepts a parameter, so how do I go around it, my first idea would be to just wrap it in another function, but is there an easier way, this seems like too much nesting
So use a function or use bind
function test1(event, param) {
console.log(param)
}
function test2(param, event) {
console.log(param)
}
const btn1 = document.querySelector('.test1')
btn1.addEventListener('click', function(event) {
test1(event, 'foo')
});
const btn2 = document.querySelector('.test2')
btn2.addEventListener('click', test2.bind(btn2, 'bar'));
<button type="button" class="test1">click 1</button>
<button type="button" class="test2">click 2</button>

How can I show and hide a button after click?

I tried this:
<button onclick="button_onclick()">Click me</button>
js:
button_onclick() = "this.style.visibility = 'hidden';"
You have a spelling error in visibility and this is not how you define functions in javascript.
You also need to pass down the element reference down as a parameter of the function.
function button_onclick(element) {
element.style.visibility = 'hidden';
}
<button onclick="button_onclick(this)">Click me</button>
OR with inline js:
<button onclick="this.style.visibility = 'hidden'">Click me</button>
There are three problems:
you're calling button_onclick() as a function but it's not defined as one.
using inline onclick is no good
you've misspelled visibality. You should use visibility instead.
If you want to handle events. the best way is to attach an event listener to the element.
const myButton = document.querySelector('.my-button')
myButton.addEventListener('click', () => {
myButton.style.visibility = 'hidden'
})
<button class="my-button">Click me</button>
Easest way of doing
<button onclick="this.style.display = 'none'">Click me</button>
Note this way of doing is not a good practice
So do it in this way
<button id="btn"> Click me </button>
<script>
const btn = document.querySelector ('#btn');
btn.addEventListener ('click', () =>{
btn.style.display = "none"
// btn.style.visibility = "hidden"
})
</script>
Thank you
try this
function button_onclick() {
document.getElementById("btn").style.visibility="hidden";
}
<button id="btn" onclick="button_onclick()">Click me</button>

Get element from which onclick function is called

I have a button with a onclick attribute which is pointing to the function test().
<button onclick="test()">Button 1</button>
<button onclick="test()">Button 2</button>
<button onclick="test()">Button 3</button>
Function test():
function test()
{
var button_name = this.html;
console.log("Im button "+ button_name);
}
How can I get informations about the clicked button?
e.g. How can i read the html?
jsfiddle: https://jsfiddle.net/c2sc9j9e/
Pass the this reference to the function, then read textContent property the text content of the node.
HTML
<button onclick="test(this)">Button 1</button>
Script
function test(clickedElement){
var button_name = clickedElement.textContent;
}
Fiddle
Four options:
Pass this into the function.
<button onclick="test(this)">Button 1</button>
and then use that argument in the function.
Hook up the handlers with addEventListener or jQuery's on, and then use this within the handler.
var buttons = document.querySelectorAll("selector-for-the-buttons");
Array.prototype.forEach.call(buttons, function(btn) {
btn.addEventListener("click", handler, false);
});
function handler() {
// Use `this` here
}
jQuery version:
$("selector-for-the-buttons").on("click", function() {
// Use `this` here
});
Hook up a single handler on a container these buttons are in, and use the target property of the event object to determine which was clicked (but note that if you use other elements within button, you'll need to loop up to the button first).
document.querySelector("selector-for-the-container").addEventListener("click", function(e) {
// Use `e.target` here
}, false);
jQuery version that handles the possibility of nested elements within the button for you:
$("selector-for-the-container").on("click", "button", function() {
// Use `this` here (note this is different from the DOM version above)
});
I came across an other extremely simple way to do it in Vanilla JS so I post it here for reference:
function whoami () {
var caller = event.target;
alert("I'm " + caller.textContent);
}
<button onclick="whoami()">Button 1</button>
<button onclick="whoami()">Button 2</button>
<button onclick="whoami()">Button 3</button>
I'm not sure about the browser support for it but it works at least on Safari, Firefox and Blink based browsers.
function test(button)
{
var button_name = button.getAttribute('name');
console.log("Im button "+ button_name);
}
<button onclick="test(this)" name="button1">Button 1</button>
<button onclick="test(this)" name="button2">Button 2</button>
<button onclick="test(this)" name="button3">Button 3</button>
If you want to use Jquery, then you can call the $(this) object in the function.
you must pass "this" to function
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(t)
{
console.log(t);
}
</script>
Here is your solution jsfiddle , using jquery.
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(button)
{
var button_name = $(button).html();
alert("Im button "+ button_name);
}
</script>
just add id to each button and pass it to your test function
and here is working jsfiddle
<button onclick="test(this.id)" id="button1">1</button>
<button onclick="test(this.id)" id="button2">2</button>
<button onclick="test(this.id)" id="button3">3</button>
<script>
function test(id)
{
var button_name = id;
alert("Im button name is : "+ button_name);
console.log("Im button name is :"+ button_name);
}
</script>
What you want is the event that triggers the click, and you do that by specifying the function call as MyFunction(event). For example:
<ul>
<li onclick="MyFunction(event)">Red</li>
<li onclick="MyFunction(event)">Orange</li>
<li onclick="MyFunction(event)">Yellow</li>
</ul>
and then your Javascript function can be:
function MyFunction(ev) {
// Now you have access to everything in the event
//- including the triggering element
var element = ev.srcElement;
}
By leaving out the (event) parameter in the specification of the onclick function call you don't get it.

How to create multiple jquery functions with one function? [duplicate]

This question already has an answer here:
Consolidate Click Functions
(1 answer)
Closed 6 years ago.
I have the below jquery functions which you can find in this code pen that I would like to simplify.
I'd like to write the below javascript more concisely by writing a function that creates all the below functions, since the only difference are the following strings: name1, name2, name3, etc.
Javascript
$('#name1').on('click', function(){
document.getElementById("name1").innerHTML = "name1";
});
$('#name2').on('click', function(){
document.getElementById("name2").innerHTML = "name2";
});
$('#name3').on('click', function(){
document.getElementById("name3").innerHTML = "name3";
});
$('#name4').on('click', function(){
document.getElementById("name4").innerHTML = "name4";
});
$('#name5').on('click', function(){
document.getElementById("name5").innerHTML = "name5";
});
$('#name6').on('click', function(){
document.getElementById("name6").innerHTML = "name6";
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
I think this is the simplest solution:
$('button').on('click', function() {
$(this).html($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
If you want this to work on specific buttons you can use $('#name1,#name2,#name3...').on.
If they all have specific class you can use $('.specific-class').on.
If they all exists inside some specific element you can use $('div#id1 button').on
And so on...
You're targeting every button on the page, so the selector can be simpler:
$('button').on('click', function(){
//
});
And you're setting the "currently clicked element" to the value of its id, which can be more general:
$('button').on('click', function(){
this.innerText = this.id;
});
Note: If this selector is overly simple (you don't want to target every button on the page), you can still use the original list of id values as a single selector. Perhaps something like:
$('button[id^="name"]').on('click', function(){
this.innerText = this.id;
});
Or even:
$('#name1, #name2, #name3, #name4, #name5, #name6').on('click', function(){
this.innerText = this.id;
});
Sometimes it's also appropriate to assign click handlers to a single parent element, especially if there could be many matching elements. Something like this:
$(document).on('click', '#name1, #name2, #name3, #name4, #name5, #name6', function(){
this.innerText = this.id;
});
The difference here is that instead of assigning the handler function to each matching element, only one handler function is assigned to the document and the selector for the target button elements is evaluated on the fly when executing that handler.
Condense your jQuery to this:
$('button[id^="name"]').on('click', function(){
var thisID = $(this).attr("id"),
thisNum = thisID.replace("name", "");
document.getElementById("name" + thisNum).innerHTML = "name" + thisNum;
});
An alternative, pure jQuery solution would be this:
$('button[id^="name"]').on('click', function(){
var t = $(this),
thisID = t.attr("id");
t.html("name" + thisID.replace("name", ""));
});

simulating click event of a different selector

I have a bunch of product buttons like:
<button class='prd-class' data-prd-id='1'>
Product 1
</button>
<button class='prd-class' data-prd-id='2'>
Product 2
</button>
And I have a button click function like so:
$('.prd-class').click(function(){
$('.prd-class').removeClass('cls-focus'); //remove any focused product
$(this).addClass('cls-focus'); //then focus on the selected one
$('#selected-prd-name').text($(this).data('prd-name'));
... etc
});
As you can see, it uses this object reference inside the function heavily.
Now there is another situation where at page load I want the lines inside this function to be executed.
Since there are multiple product buttons, I want to ensure that the I am simulating the click event of the required one.
$(document).ready(function()
{
$("button[data-prd-id='"+prd_id+"']").click();
});
But this does not work. How can I change the code to execute the code lines correctly?
I am not sure about your requirements. However, this demo might give you some ideas to resolve your issues.
HTML:-
<button class='prd-class' data-prd-id='1'>Product 1</button>
<button class='prd-class' data-prd-id='2'>Product 2</button>
<div>
Selected Product ID: <span id="selected-prd-name"></span>
</div>
CSS:-
.cls-focus {
border: 1px solid red;
background-color: brown;
}
JavaScript:-
(function () {
var $prdClass = $('.prd-class'),
$selectedPrdId = $('#selected-prd-name'),
prdClassClickHander = function () {
var $self = $(this);
$prdClass.removeClass('cls-focus');
$self.addClass('cls-focus');
$selectedPrdId.text($self.data('prd-id'));
},
init = function () {
$prdClass.on("click", prdClassClickHander);
};
$(document).ready(init);
}());
// Simulate the click on DOMReady
$(document).ready(function () {
var prd_id = 1;
$("button[data-prd-id='" + prd_id + "']").trigger('click');
});
JSFiddle Demo:-
http://jsfiddle.net/w3devjs/e27jQ/

Categories