Novice trying to make pagination in JavaScript - javascript

Trying to make it so this counter with buttons increases or decreases based on clicks, however on the first click the counter doesn't increase. If I do + 1 it will but then will stop. ++works but only after first click. Trying to learn easy way to resolve my code that isn't a drastic change.
https://jsfiddle.net/sy0ohtrc/
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.innerHTML = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
var elPageIncrease = document.getElementById("currentPage");
elPageIncrease.innerHTML = pageCount++;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
var elPageDecrease = document.getElementById("currentPage");
elPageDecrease.innerHTML = pageCount--;
}

You should use --/++ before the counter because when you use the increment/decrement operator after, the value will be returned before the it increased/decreased.
AND there is no need for declaring 3 time the same element.
Finally change the innerHTML to textContent (and if you want to know why read this thread).
Your code should look something like that:
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.textContent = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
// var elPageIncrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = ++pageCount;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
// var elPageDecrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = --pageCount;
}
<div class="pager">
<button id="prevButton">prev</button>
<p class="pageNumber" id="currentPage"></p>
<button id="nextButton">next</button>
</div>

Related

how to exit from a function in javascript?

I am using this codepen template
https://codepen.io/stevethorson/pen/nisBh for quiz competition. I have 10 div elements all are set to display none except the first div, when this timer gets reset, it will change my next div display and hide the previous div display.
how to stop that timer resetting when it complete 10 resets and make my 10th div not to hide? all the id of div are in array.
the changes i made at the bottom of js code in that template is,
var Timer;
let ids=["aq","bq","cq","dq","eq","fq","gq","hq","iq","jq"];
var i=0;
var j=1;
$(document).ready(function() {
var callbackFunction = function(){
Timer.reset(2);
i+=1;
j+=1;
$('h3').html('Question Number:'+j+'');
document.getElementById(ids[i-1]).style.display = "none";
document.getElementById(ids[i]).style.display = "";
};
Timer = new radialTimer(callbackFunction);
Timer.init("timer", 2);
});
so i want my last div to appear permanently
Timer.start(t);
while (j >2) {
timer.stop(a); // name that callback function as a and if it gets incremented i,e resetted untill some reseets, just use while loop and stop that funcion a.
}
}
}
var Timer;
let ids=["aq","bq","cq"];
var i=0;
var j=1;
$(document).ready(function() {
var callbackFunction = function(a){ //function a
Timer.reset(2);
i+=1;
j+=1;
$('h3').html('Question:'+j+'');
document.getElementById(ids[i-1]).style.display = "none";
document.getElementById(ids[i]).style.display = "";
};
Timer = new radialTimer(callbackFunction);
Timer.init("timer", 2);
});

Is there a way to make a function that can be accessed later in a google chrome extension?

I am trying to make an extension that makes a button which then executes a function, however, because the extension executes a javascript file after the page loads. However, when I create the button I want to run a function. Is there a way I can store a function and variables that can be run and access later by the button?
var effect = [[1,100],[2,32], [5,3]];
var points = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][0];};return adding;})()
var score = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][1];};return adding;})()
var percentage=(score/points*100).toString()+"%";
this.effect = effect;
this.points = points;
this.score = score;
var percentage = points/score;
function list_effect(){
var effect_string = "";
for(var i = 0; i<effect.length;i++){
effect_string += ((points-effect[i][0])/score) - ((points)/score);
}
alert(effect_string);
}
if(percentage == 'NaN%'){
// alert('ERROR');
}else{
document.getElementsByClassName("agenda")[0].innerHTML = "<button type=\'button\' id=\'get_list\'>Get List</button>"+ document.getElementsByClassName("agenda")[0].innerHTML;
document.getElementsByClassName("agenda")[0].innerHTML += "<script>" + "this.effect=" + effect.toString() + ";\nthis.points=" + points.toString()+ ";\nthis.score=" + score.toString() +"document.getElementById(\"get_list\").addEventListener(\"onclick\", list_effect());" + "</script>"
}
I have tryied useing this. however that does not work
<script> won't run when added via innerHTML, you should add it using appendChild
normally you don't need to add a <script> element at all, just use createElement and attach the listeners directly
var button = document.createElement('button');
button.id = 'get_list';
button.onclick = function (e) {
// use your variables here directly
};
// clear the previous contents
document.querySelector('.agenda').textContent = '';
// add the button
document.querySelector('.agenda').appendChild(button);

i can add textbox with button but i don't know how to remove

var emails = document.getElementById('emails'),
add_link = document.createElement('a'),
template = emails.getElementsByTagName('div'),
current = template.length,
max = 20;
template = template[0];
submit1.onclick = function () {
var new_field = template.cloneNode(true);
current += 1;
new_field.innerHTML = new_field.innerHTML.replace(/1/g, current);
emails.appendChild(new_field);
if (current === max) {
add_link.onclick = null;
document.body.removeChild(add_link);
}
return false;
};
document.body.appendChild(add_link);
copy from this link
add multiple textbox using button click in javascript
how to create button for remove ,please tell me
Try using something like this.
elememt.parentNode.removeChild(element);
This question has been asked and posted on this site. Look at this link.
Remove an Element with Javascript

How to interate an array with navigation menu buttons (first, previous, next, last)

Well, one more question. Since I started learning javascript short time ago, I am almost obsessed trying new things! Here it goes:
Let's say that I have an array of strings and I want to iterate on it with a navigation menu with the buttons FIRST, PREVIOUS, NEXT, LAST.
Look at this code:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
function generatepage(article) {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
I also figured out that generatepage(thearray.length -1)would be the call for the last article, so I have solved two buttons (before generating new content I would erase it with innerHTMLbut what I cannot think about how to do are the PREVIOUS and NEXT buttons...
Do you have any suggestion about how should I get started to make working PREVIOUS and NEXT?
I attach a JSFiddle
Thank you so much for any advice!
You can save the active page in a variable outside the function:
var page = 0;
Then you don’t need to bring any page into generatepage():
function generatepage() {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[page]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
Now you can control the page from outside the function:
var next = function() {
if ( page < page.length-1 ) { page++; }
}
var prev = function() {
if ( page ) { page--; }
}
So to show the first page:
page = 0;
generatepage()
And the next:
next();
generatepage()
etc.... There are other ways too of course but this might give you an idea.
You can save a variable outside the scope of the function to memorize the current article
when you add Eventlisteners to the buttons you can call the next and previous item
but you should somehow replace the content of the div with the next one instead of appending it (i don't know a thing about manipulating dom elements)
you could try something like this:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
var currentarticle
function generatepage(article) {
if(thearray[article]) {
currentarticle = article
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.innerHTML= paragraph.innerHTML
}else {
return false
}
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
document.getElementById("next").addEventListener("click",function() {
generatepage(currentarticle + 1)
});
document.getElementById("previous").addEventListener("click",function() {
generatepage(currentarticle - 1)
});
document.getElementById("last").addEventListener("click",function() {
generatepage(thearray.length - 1)
});
document.getElementById("first").addEventListener("click",function() {
generatepage(0)
});
​
heres the Fiddle

How can I create multiple ul-lists dynamically?

I have a <ul> "ul-list-one", which contains a number of checkboxes. If I check the checkbox and click the move button it means that it will move to another <ul> "ul-list-two", and the checked checkbox will be removed from the previous, which here would be "ul-list-one".
In "ul-list-two" I can do the same, and it moves to the next, this time "ul-list-three".
Note: "ul-list-two" and "ul-li-three" will be created dynamically.
Here I have done some work, but how can I be able to create multiple <ul>s dynamically?
$('#mer').click( function() {
var txtBox = "";
var txtstatus = false;
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var val=$("#hidden_id").val();
var to = 'ch';
if (!t.is(':checked')){
var swap = to;
to = from;
from = swap;
} else {
txtstatus = true;
}
$(':checkbox:checked').attr('disabled', true);
$('#'+to).append(t.attr('name', to).parent());
$('#ch').addClass('br');
});
if(txtstatus){
txtBox = "<input type='text' value=''>";
$('#ch').after(txtBox);
}
});
//close buttom code
$('#cls').click( function() {
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var to = 'ch';
if (t.is(':checked')){
var swap = to;
to = from;
from = swap;
}
$(':checkbox:checked').attr('disabled', false);
$(':checkbox:checked').attr('checked', false);
$('#'+from).append(t.attr('name', from).parent());
});
});
Not the prettiest thing I have ever written. If you want to leave the empty ul's, just comment out the removeEmpties call. I didn't worry about checkbox order, but it would be easy to implement in a separate function after the checkbox is moved. I also assumed you wouldn't want them to move backward beyond the initial ul. If you want that functionality, you could just add another else if to the move function.
http://jsfiddle.net/pJgyu/13225/

Categories