Javascript event triggering creating multiple button .on('click) - javascript

I'm using HTML slim for the code below.
.page
.paper
button.button.js-copier I copy things
- content_for :js_includes do
javascript:
var startingHtml = $('.page').html();
function initializePlugin() {
$('.js-copier').each(function () {
$(this).on('click', function () {
$('.page').append(startingHtml);
$(document).trigger('page-refreshed');
});
});
}
// Run it right away
initializePlugin();
$(document).on('page-refreshed', initializePlugin);
Is there a way to fix the fact that when I click on the "I copy things" button, it creates multiple copies of the button as it is iterating over all the button from the button that was selected?
Also, is there a better way to write this code. All I'm trying to do is duplicate the button anytime I click on any buttons(first and any new button created buttons)
-Anthony

First change this:
$('.js-copier').each(function () {
$(this).on('click', function () {
...
to this:
$('.page').on('click', '.js-copier', function () {
...
Read this to understand https://learn.jquery.com/events/event-delegation/#event-propagation
Then remove the 'page-refreshed' event because you don't need it:
$(document).trigger('page-refreshed');
...
$(document).on('page-refreshed', initializePlugin);
Demo solution:
var startingHtml = $('.page').html();
function initializePlugin() {
$('.page').on('click', '.js-copier', function () {
$('.page').append(startingHtml);
});
}
// Run it right away
initializePlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
<div class="paper">
<button class="button js-copier"> I copy things</button>
</div>
</div>

Related

Create clone on another function with jquery

It shows a message 'Hi' when I click on 'ShoW',
But when I click on the next option 'ShoW', it does not show a message.
$('.btn').on("click", function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>
What code should I add for JS?
This is because the event handler you created is bound to objects that existed when it was created:
$('.btn').on("click", function () {
This will only work for .btn elements that were already available at the time this line of code ran - it is not evaluated by jQuery again.
Instead, use this format for binding the event, which will pick up dynamically created elements:
$(document).on('click', '.btn', function () {
Seen here in this working snippet:
$(document).on('click', '.btn', function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>
You have to set event once more again after clone.
then, you can declare your event callback as a function, and set event again after cloning on the cloned element, like this:
function appendShowButton() {
alert('Hi');
$('.box .btn').remove();
var newEl = $('.btn').clone().appendTo('.box');
newEl.on('click', appendShowButton);
return false;
}
$('.btn').on("click", appendShowButton);

jquery javascript click function from within a function

I have an external JS file that contains the following jQuery code:
var globalNames = { next: 'input[name="next"]'};
var globalElements = { next: $e.find(globalNames.next) };
initQuiz: function() {
globalElements.next.click(function () {
if (y.forcingQuestionSolve && !j[c.index()] && (y.quizSummeryHide || !y.reviewQustion)) {
alert(WpProQuizGlobal.questionNotSolved);
return false
}
i.methode.nextQuestion()
}
);
the globalElements.next.click function is triggered by a click on a button:
<input type="button" name="next" value="Next" class="Button" ">
What I would like to do is call this p.next.click function from a Input Checkbox click.
I have added the following code:
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('next').trigger('click');
});
</script>
As you can see, I have tried to call the trigger event but its not working.
I have to note that the 2 jQuery statements are not combined in document, they are separate.
EDIT: Added Correct Variables (global*)
Hi i think you only forgot to dedicate the button which has to be triggered.
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('[name=next]').trigger('click');
// $('.Button').trigger('click');
});
thanks everyone.. I used the following code from Calvin Nunes-
$("[name='next']").trigger('click');
Craig.

Call a function in javascript only after page load

I have a button that is set up to call a javascript function to automatically activate a "tab" on a page. When that tab is loaded, there are subtabs that display. I am trying to set it up so that one of the subtabs is also automatically activated when the button is clicked.
Currently I can get the first tab to select, but I can't get the subtab to select. #detailsTab is the id of the first tab. #personal-information is the id of the subtab I am trying to select.
The following is what I have.
This is all in the same file:
HTML:
<button class="button button--primary button--sm" onclick="viewDetials()">View Details</button>
Javascript:
<script type="text/javascript">
function viewDetials() {
$("#detailsTab").click();
personalSubTab();
}
window.onload = function personalSubTab() {
$("#personal-information").click();
}
</script>
Try combining your functions and adding a short delay for the subtab.
function viewDetials() {
$("#detailsTab").click();
setTimeout(function(){
$("#personal-information").click();
}, 200); // This value can be tweaked
}
The following will be called when the document is ready.
<script type="text/javascript">
function viewDetials() {
$("#detailsTab").click();
personalSubTab();
}
function personalSubTab() {
$("#personal-information").click();
}
// Document ready
$(function () {
personalSubTab();
});
</script>
I'm not exactly sure what you want to do - but if you want to generate a click event on another button/div use trigger, not click - like this:
function personalSubTab() {
$("#personal-information").trigger('click');}

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/

Calling a specific function alone in javascript or jquery

i have a piece of code like this.
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.
how to do that?
It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick
You can see that parameters it mentions an $event object. So your html will become:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
and then your javascript will become:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle: http://jsfiddle.net/rtCP3/32/
Instead calling functions there inline use jquery to solve this issue:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});
For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating
<div class="box" onclick="displayinfo(event)">
Then change js to:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
DEMO: http://jsfiddle.net/MvgTd/
whatever you are getting.stopPropagation();
in your case
$event.stopPropagation();

Categories