Callback function not working in following code? - javascript

the following code should show a random quote. But it returning nothing. Just showing the html page layout. Why following javascript callback function isn't working:
$(document).ready(function() {
function cb() {
var addr = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
$.getJSON(addr, function(rslt) {
return rslt;
});
};
function qte(rslt) {
$("#qti").html(rslt[0].content);
$("#athr").html(rslt[0].title);
};
qte(cb);
$("#nqt").on("click", function() {
qte(cb);
});
$("#tit").on("click", function() {
window.open("https://twitter.com/intent/tweet?text=" + encodeURIComponent(qwe));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<h1 class="text-center" style="margin-top:20px;">Random Quote Generator</h1>
<div class="box">
<div class="qt">
<span id="qti"></span>
</div>
<div class="athr">- <span id="athr"></span></div>
<div style="width:100%; clear:both; margin-left:auto; margin-right:auto; margin-top:6%;">
<button class="btn" title="twitt it!" id="tit"><i class="fa fa-twitter"></i></button>
<button class="btn pull-right" id="nqt">New Quote</button>
</div>
</div>
</div>

You can do like this. Use $.when to trigger the qte function once the response is available from the asynchronous call.
$(document).ready(function() {
function cb() {
// changed http to https to avoid blockrd content
var addr = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
// returning the 'promise' from this function
return $.getJSON(addr, function(rslt) {
return rslt;
});
};
// when cb function has finished execution using its result to populate the fields
$.when(cb()).done(function(rslt){
$("#qti").html(rslt[0].content);
$("#athr").html(rslt[0].title);
});
// rst of code
});
DEMO

Related

How do I remove a specific div out of many using one function in JavaScript?

I'm learning JavaScript and this is a practice scenario for me.
What I have already is a button that clones content, and within that content that has been cloned, there is a button to remove it.
When I click the button that prompts you to remove the content, it removes the first set of content.
What I want to happen is when you click the button that prompts you to remove the content, it removes the content related to that button and nothing else.
This is the CodePen link.
https://codepen.io/JosephChunta/pen/YzwwgvQ
Here is the code.
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent() {
var x = document.getElementById("content").parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden {
display: none;
}
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent()">Remove this</button>
<hr />
</div>
</div>
</div>
When you'r trying to remove by ID, it takes the first ID it finds.
To remove the correct content, send this onclick.
<button onclick="removeContent(this)">Remove this</button>
And handle it in your function:
function removeContent(el) {
el.parentNode.remove();
}
Example:
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent(el) {
el.parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden { display: none; }
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent(this)">Remove this</button>
<hr />
</div>
</div>
</div>
In your remove button, do this:
<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>
And in your javascript:
function removeContent(element) {
element.parentNode.remove();
}

take div's id by referencing this

Hello everyone im trying to get the id of a div through a function in javascript like this:
<div id="txtHint" onload="getId(this);"></div>
The function is located just before </body> tag of my html page
function getId(theId) {
var name = document.getElementById(theId);
}
In the body of my html page i have a button:
<button type="button" onclick="alert(getId())">get</button>
I receive an undefined alert on clicking
How do i get the div's id?
Anyone can help?
Though I don't know the use case of this, you can pass the id to the function and return that from the function:
function getId(theId) {
var name = document.getElementById(theId);
return name.id;
}
<div id="txtHint"></div>
<button type="button" onclick="alert(getId('txtHint'))">get</button>
Update: If you want to get all id's by tag, simple pass the tag to the function and get all the id's of those element:
function getId(el) {
var element = document.querySelectorAll(el);
var id = [...element].map(i=>i.id).filter(i=>i);
return id;
}
<div id="txtHint1">First</div>
<div id="txtHint2">Second</div>
<div id="txtHint3">Third</div>
<div id="txtHint4">Fourth</div>
<button type="button" onclick="alert(getId('div'))">get</button>
The way your functions is written the only way is to have global variable
var divId = null;
function getId(div) {
divId = div.id;
}
function getId() {
alert(divId);
}
And here is my suggetions on doing it
First way is to "mark" the div at onload event and get the id of it using this "mark"
function markDiv(thisDiv) {
thisDiv.classList.add('mark')
}
function getMarkedDiv() {
var div = document.querySelector('.mark');
alert(div.id);
}
<div id="Mark" onload="markDiv(this)" class="mark"></div>
<button onclick="getMarkedDiv()">button</button>
Another way is to wrap the button and the div inside one parent
function getMySiblingId(button) {
alert(button.parentElement.firstElementChild.id);
}
<div id="Parent">
<div id="Mark"></div>
<button onclick="getMySiblingId(this)">Button</button>
</div>
Or the easiest way is to wrap button inside the desired div
function getId(btn) {
alert(btn.parentElement.id);
}
<div id="Mark">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Alice">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Charlie">
<button onclick="getId(this)">Click me</button>
</div>
Of course in all this scenarios i didn't assume that you want to get ids of multiple divs
so i remade the code
function divField(theDivFieldId) {
var name = document.getElementById(theDivFieldId);
return name.id;
}
html
<div id="txtHint" onload="alert(divField(this));"></div>
and nothing happens

Get Data Value from Parent or Closest Div

I have this function that I am trying to get the data value of the outside div but I can't seem to get it to work, here is my code:
I want the variable test to have the value of 1000. But I get undefined.
function View() {
var test = $(this).Parent().val;
}
function Hide() {
var test = $(this).Parent().val;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
<a onclick="View();">View</a>
<a onclick="Hide();">Hide</a>
</div>
function View(anchor) {
var test = $(anchor).parent().data('value');
console.log(test);
}
function Hide(anchor) {
var test = $(anchor).parent().data('value');
console.log(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
<a onclick="View(this);">view</a>
<a onclick="Hide(this);">hide</a>
</div>
Here is a JQuery solution for the problem.
$('#hide').click(function() {
alert($(this).parent().data('value'));
})
$('#view').click(function() {
alert($(this).parent().data('value'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
<a id="view">View</a>
<a id="hide">Hide</a>
</div>

Invoke function only on the selected ng-repeat element

Currently I am trying to fetch some data using JSON and have structured it over my website using ng-repeat.
The problem is that on ng-click, on any newly created element the function invokes on each element as well. I have also tried using the this operator but it doesnt seem to work on angularjs.
I have created a dummy problem similar to mine.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<div ng-repeat="aplhabet in word">
<button style="width:50px; margin: 5px" ng-click="addDiv()">
<b>{{aplhabet}}</b>
</button>
<section ng-show="newdiv">functionInvoked</section>
</div>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope){
$scope.word = 'STRINGDEMO';
$scope.addDiv = function () {
$scope.newdiv = true;
}
}
</script>
</body>
</html>
As you might notice whenever you click on any button the function runs for each element. I need help to understand how to pass any identifier in this function so that the function is invoked only on the element clicked.
you need an object array to achieve this. simply use a for loop to convert this to an array of object.
for(key in $scope.word){
$scope.wordArr.push({
letter : $scope.word[key],
newDiv : false
})
}
use the new array as ng-repeat. to print letter use <b>{{aplhabet.letter}}</b>
<div ng-repeat="aplhabet in wordArr">
<button style="width:50px; margin: 5px" ng-click="addDiv(aplhabet)">
<b>{{aplhabet.letter}}</b>
</button>
<section ng-show="aplhabet.newdiv">functionInvoked
</section>
</div>
in the ng-click pass the whole object as a parameter and change the newDiv to true
Demo
var myApp = angular.module('myApp',[]);
function MyCtrl($scope){
$scope.word = 'STRINGDEMO';
$scope.wordArr = [];
for(key in $scope.word){
$scope.wordArr.push({
letter : $scope.word[key],
newDiv : false
})
}
$scope.addDiv = function (aplhabet) {
aplhabet.newdiv = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="aplhabet in wordArr">
<button style="width:50px; margin: 5px" ng-click="addDiv(aplhabet)">
<b>{{aplhabet.letter}}</b>
</button>
<section ng-show="aplhabet.newdiv">functionInvoked
</section>
</div>
</div>
You need to pass $index
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<div ng-repeat="aplhabet in word track by $index">
<button style="width:50px; margin: 5px" ng-click="addDiv($index)">
<b>{{aplhabet}}</b>
</button>
<section ng-show="newdiv">functionInvoked</section>
</div>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope){
$scope.word = 'STRINGDEMO';
$scope.addDiv = function (index) {
//do your stuff here
}
}
</script>
</body>
</html>

Why isn't my JavaScript printing to my HTML?

I learned AngularJS before I learned how to connect vanilla JS to HTML. When I run this code in my browser, the console.logs work, but the number 3 isn't showing up in my first die.
Can you help me fix my code?
JavaScript:
var roll = document.getElementById('roll');
function Dice() {
Document.write('1');
}
function printNumber() {
var one = document.getElementById("one");
one.innterHTML = "3";
console.log('printNumber called!');
}
roll.onclick = function() {
printNumber();
console.log('rolled!');
};
HTML:
<div class="row">
<div class="dice" id="one">
</div>
<div class="dice" id="two">
2
</div>
</div>
<div class="row">
<div class="button" id="roll">Roll the dice!</div>
</div>
<script type="text/javascript" src="dice.js"></script>
innter should be inner and Document should be document.
function Dice() {
document.write('1');
}
function printNumber() {
var one = document.getElementById("one");
one.innerHTML = "3";
console.log('printNumber called!');
}
roll.onclick = function() {
printNumber();
console.log('rolled!');
};

Categories

Resources