Changing Variable Value on Click in Javascript - javascript

Okay, so I am using the dribbble API to GET my works from dribbble
I set up a few VAR's to help with the process;
var dribbble = 'crobertson97';
var limit = '10'; //items per page
var per_page = '&per_page='+limit+''; //url
var accessToken = '12345678910'; //client
var url = 'https://api.dribbble.com/v1/users/'+dribbble+'/shots/?access_token='+accessToken+'&callback=?'+per_page; //url
I want to add a view more button that if clicked will do three things;
the button <a id="readmore" class="btn btn-success white"> View More</a>
Change the text of the button from view more to view less
Change the var limit = 10 to 20
3.Be able to revert --> view less

Add an onclick function to the html:
<a id="readmore" class="btn btn-success white" onclick="buttonClick(this)"> View More</a>
And create the following function in the JS:
function buttonClick(but) {
if(limit==10) {
limit = 20;
but.innerHTML= "View less";
} else {
limit = 10;
but.innerHTML = "View more";
}
}
There's still the display of the content to manage, but you didn't give much information about what you want and how the data is given!

Pretty easy, using modern web API.
readmore.addEventListener('click', readmoreless);
var limit = 10;
function readmoreless(){
if(limit == 10){
readmore.innerHTML = "View Less";
limit = 20;
} else {
readmore.innerHTML = "View More";
limit = 10;
}
}
<a id="readmore" class="btn btn-success white">View More</a>

Related

Active nav bar doesn't change the first time

I am trying to change navigation a tag color when the user clicks on the <a> tag. The JS is working fine, except the first time the user clicks on the <a> tag; only in the second time the a tag color changes.
JavaScript:
function toggleNav(pageId){
activeColor();
var href = 'html/' + pageId + '.html';
window.onload = document.getElementById('main').innerHTML =
loadPage(href);
}
function activeColor(){
var header = document.getElementById("allNav");
var btns = header.getElementsByClassName("notActive");
for (var i = 0; i < btns.length; i++) {
var button1 = btns[i];
button1.addEventListener("click" ,
function() {
var current = document.getElementsByClassName(" active");
console.log(current.length);
for (var i = 0; i < current.length + 1; i++) {
current[0].className = current[0].className.replace("
active", "");
}
var myString = this.id;
var stringLength = myString.length;
var lastChar = myString.charAt(stringLength - 1);
if(lastChar == "2"){
var add = document.getElementById(this.id);
var id2Nmae = add.id.slice(0, -1);
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
else{
var add = document.getElementById(this.id);
var id2Nmae = add.id + "2";
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
});
}
}
HTML :
<div id="allNav">
<div class="sidebar" id="mySidebar" style="display:block">
<button id="open" onclick="Toggle()">
<a ><i class="fas fa-bars"></i></a>
</button>
<i class="glyphicon glyphicon-screenshot"></i>
<i class="glyphicon glyphicon-exclamation-sign"></i>
<i class="fas fa-burn"></i>
<i class="fas fa-utensils"></i>
<i class="fa fa-line-chart"></i>
<i class="far fa-comments"></i>
<i class="fas fa-bell"></i>
</div>
I succeeded to solve the problem, It was an issue I made by the DOM path not correct.
In the first time the page loads, the default load was the "goals" id by the next JS code:
var href = 'html/goals.html';
window.onload = document.getElementById('main').innerHTML = loadPage(href);
In this why the "addEventListener" needed to load at the first time and only in the second time the function can run.
I changed the default function to:
toggleNav('goals')
I hope I helped if somebody will experience the same issue.
Thanks for the help.
I ran your script and in the console I got
Uncaught TypeError: Cannot read property 'id' of null
(in chrome dev tools) Have you checked the element view (next to console) to see how the javascript is interacting with the HTML?
from looking at the code, the number "2" is for ids that are selected, however, everything ends with the number 2 and it is never actually removed. Is that intentional?
The loop doesn't seem to like "this.id" as it loses the reference (error above).
have you put in alerts to see where the pointer is in the loop?

How can I use innerHTML to create a clickable link based on user's input?

I want to prompt the user to enter a website, and then have that website show on the page as a clickable link. Can someone help me figure out why this isn't working?
HTML:
<h5 class="user-output">My favorite website is <span id="favorite-
website">...</span></h5>
<button class="button-primary" onclick=app.setWebsite()>Set
Website</button>
When the user clicks 'Set Website' a dialog box with the prompt should pop up, but with the code below no box shows.
JS:
app.setWebsite = function setWebsite() {
var favWebsiteInput = prompt("What is your favorite website?")
var getWebsite = document.getElementById("favorite-website")
getWebsite.innerHTML = <a href="favWebsiteInput">
<span class="favorite-website"></span>find out here!</a>
HTML:
<h5 class="user-output">My favorite website is
<span id="favorite-website">...</span>
</h5>
<button class="button-primary" onclick="app.setWebsite()">Set Website</button>
JS:
app = {};
app.setWebsite = function() {
var favWebsiteInput = prompt("What is your favorite website?");
var getWebsite = document.getElementById("favorite-website");
getWebsite.innerHTML = '<a href=http://' + favWebsiteInput + '>find out here!</a>';
};
This code would work.
if(!app)app = {};
app.setWebsite = function setWebsite() {
var favWebsiteInput = prompt("What is your favorite website?")
var getWebsite = document.getElementById("favorite-website")
getWebsite.innerHTML = '<span class="favorite-website"></span>find out here!';
}
app.website = function setWebsite()
{
var favWebsite = document.getElementById('favourite-website');
favWebsite.addEventListener("click", function(){
favWebsite.innerHTML = `<a href="`+favWebsiteInput+`">
<span class="favorite-website"></span>find out here!</a>`;
});
}

How to add working dropify inputs dynamically

I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

Change a button label using Javascript

I have a submit button which I am sharing between 'Create' and 'Update'. I want the following labels depending on my page state:
Create = Submit
Update = Update
These buttons also have an image at the front of them using glyphicon but the image will be the same for both buttons.
To get to my page states (listed above) I have other JavaScript functions which the relevant buttons call.
All my code is below. I am struggling as I am fairly new to JavaScript and I now I can do it by adding using Value but this doesn't work due to my image.
Edit Button HTML
<button type="button"class="btn btn-default" name="RegCashMove_Edit_Button" onclick='RegCashMoveEdit()'>
<span class="glyphicon glyphicon-pencil" title="Edit" style="vertical-align: middle"></span>
</button>
Create Button HTML
<button type="button" class="btn btn-default" name="RegCashMove_Create_Button" onclick='RegCashMoveCreate()'>
<span class="glyphicon glyphicon-plus"></span> Create
</button>
Variable Button HTML
This is the button I want the label to be variable on. At the moment its 'Submit'
<button name="RegularCashMovements_Submit_Button" class="btn btn-default" id="RegularCashMovements_Submit_Button" type="submit">
<span class="glyphicon glyphicon-ok"></span> Submit
</button>
JavaScript function for 'Create' button
function RegCashMoveCreate(txt) {
document.getElementById('selection').value = "Create";
document.getElementById('index').value = "";
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_To_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_Amount_TextBox').value = "";
document.getElementById('RegCashMove_Frequency_DropDownList').value = "0";
};
JavaScript function for 'Edit' button
function RegCashMoveEdit(txt, from, to, amount, frequency, index) {
document.getElementById('selection').value = "Edit"
document.getElementById('index').value = index;
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = from;
document.getElementById('RegCashMove_To_DropDownList').value = to;
document.getElementById('RegCashMove_Amount_TextBox').value = amount;
document.getElementById('RegCashMove_Frequency_DropDownList').value = frequency;
};
I no I should be able to add a variable in each of my JavaScript function to display the relevant label but my issue is getting it on the button with my image
You can set the textual content of a HTML element with the "textContent" property ("innerText" in IE < 9):
var button = document.getElementById('RegularCashMovements');
button.innerText = button.textContent = 'new text';
The span element inside the button element should not be removed.
If you also want to change the title of the span do it like that:
for (var index = 0; index < button.childNodes.length; index++) {
if (button.childNodes[index].tagName == 'SPAN') {
button.childNodes[index].title = 'new title';
break;
}
}
You need to iterate through all child nodes of the button, instead of taking the first one, because than you will get the text content of the button again.
I hope i understood your problem. I also have to say, that your javascript is very procedural and inperformant because of all the "display: none;" and innerHTML accesses. My tip for you would be to think more objective and put all elements you need to hide in one container element and hide that one.

Toggle on Yes/No buttons to continue on in survey

I want to know how to make sure either the Yes or No button is toggled in my survey in order to continue (so if either Yes or No has been clicked, the nextQuestion function can continue. If Yes or No has not been clicked, I will give an alert to the user to please make a selection). I currently have the progress bar and question updating in the same function. I figured it would make sense to add this bit to it but I am getting confused.
var index_question = 0;
var question_number = 2;
var progress_question = 1;
var percentage = 0;
function nextQuestion(){
if (index_question < 4) && ($(".btn-success").button('toggle')) {
<!-- Question # and Question Text -->
document.getElementById("questionArea").innerHTML = questionSet[index_question];
index_question ++;
document.getElementById("questionNum").innerHTML = [question_number];
question_number ++;
<!-- Progress Bar -->
percentage = ((([progress_question])*(100))/(5));
progress_question++;
$(".progress-bar").width([percentage] + "%");
}
<!-- Survey Completed -->
else {
$(".progress-bar").width("100%");
alert("Thank you for completing the survey!")
}
}
<td><button class="btn btn-success" type="button" onclick="questionDecision">Yes</button></td>
<td><button class="btn btn-danger" type="button" onclick="questionDecision">No</button></td>
function questionDecision() {
$(".btn btn-success").button('toggle');
$(".btn btn-danger").button('toggle');
}
One option is to have a variable in the Javascript like var answered_question = False;, which is set to True in your questionDecision function after they have made a choice. Before advancing the user to the next question or updating the progress bar, always check if(clicked_yes_or_no==True){ }.

Categories

Resources