How to order div positioning in javascript? - javascript

I'm trying to order div depending on what comes from the url, let me explain,
http://127.0.0.1:5500/index2.html?group=teams&card=pro
I have the "teams" group and I have the card that starts with "pro"
then what you should do is order the cards depending on what you put in the url, that is, if it is "pro" let the "pro" card be first, if I search for ultra it leaves the "ultra" card first.
<div class="container-equipos" id="equipos">
<div class="equipos" data-equipo="1">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Pro</p>
</div>
<div class="equipos" data-equipo="2">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Plus</p>
</div>
<div class="equipos" data-equipo="3">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Ultra</p>
</div>
var urlSearchParams = new URLSearchParams(window.location.search);
if (urlSearchParams) {
var card = urlSearchParams.get('card')
var group = urlSearchParams.get('group')
var tab = urlSearchParams.get('tab')
var equipos = document.querySelector('#equipos');
var internet = document.querySelector('#internet');
var planes = document.querySelector('#planes');
switch(group){
case 'equipos': {
equipos.classList.add('active');
if(equipos.classList.contains('active')){
var $wrap = $('.container-equipos');
$wrap.find('.equipos').sort(function(a, b){
if(card == 'pro'){
return 1;
}else if(card == 'plus'){
//I'm missing this part
} else if(card == 'ultra'){
return -1;
}
}
}).appendTo($wrap);
}
break;
}
}
}
This is what I have, but I don't know how to order them with sort, since sort orders me from the first to the last or from the last to the first but not the second... thanks for help

Related

How to push and pop the details into the array in javascript based on the selection of cards?

I am having 6 bootstrap cards in my web page where every card consists of details like id and content. When I clicked the card the details of the card should be pushed into the array and when I clicked the same card the details should be popped from the array.
My html page in django:
<div class="row">
{% for j in goal %}
<div class="col-4" onclick="getGoal({{j.id}})">
<div class="card4 mt-3" id="room_{{j.id}}" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_{{j.id}}"><b>{{j.goal}}</b></p>
</center>
</div>
</div>
</div>
{% endfor %}
My js code is
var goal = []
function getGoal(id ,content){
if (goal !== []) {
for(var i=0; i<goal.length; i++){
if(goal[i].id == id) {
var index = goal.indexOf(goal[i])
if (index !== -1) {
goal.splice(index, 1);
}
}
}
}else {
var data = {id: id, content: $("#cont_"+id).text()}
var x = JSON.stringify(data)
goal.push(x)
console.log(goal)
}
}
var storedNames = JSON.parse(localStorage.getItem("goal"))
Is the JS code correct for my requirement?
As you can see after adding indentations, you html code is not valide where do you close the center tag ? Else where / how do you call getGoal and why do you have the content parameter if you don't use it ?
var goal = []
function getGoal(id ){
if (goal.length > 0) {
let index = goal.findIndex(x=>x.id == id)
if(index != -1){
goal.splice(index, 1);
}
else{
var data = {id: id, content: $("#cont_"+id).text()}
goal.push(data)
}
}else {
var data = {id: id, content: $("#cont_"+id).text()}
//var x = JSON.stringify(data)
goal.push(data)
console.log(goal)
}
}
var storedNames = JSON.parse(localStorage.getItem("goal"))
try It

How to re-perform the javascript keyup function automatically when navigating back to the page?

Is there any way to keep the javascript keyup function result when navigating back to the page?
In my book list page, I have a search option that searches the title available on the page with javascript. Say I type harr in the search box, and the Harry Potter result appears. If I click the link to the Harry Potter page and come back again to the index page, the keyword harr still in there in the search box but it is not displaying the result obviously rather the whole page.
Is there any way that when I come back to the index page and if there is any input in the search box, the js will run again with the keyword so that it'll just show the result, not the entire page?
Here is the snippet: As the snippet doesn't support multiple pages, here is the project in codepen where I've created dummy pages for the book Harry Potter.
const searchBar = document.forms['search-books'].querySelector('input');
searchBar.addEventListener('keyup', function(e) {
const term = e.target.value.toLocaleLowerCase();
const books = document.getElementsByTagName('h5');
var notAvailable = document.getElementById('notAvailable');
var hasResults = false;
Array.from(books).forEach(function(book) {
const title = book.textContent;
if (title.toLowerCase().indexOf(term) != -1) {
book.parentElement.parentElement.style.display = 'flex';
hasResults = true;
} else {
book.parentElement.parentElement.style.display = 'none';
}
});
notAvailable.style.display = hasResults ? 'none' : 'block';
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<form id="search-books">
<input type="text" placeholder="Search a book ... ">
</form>
<div class="container">
<div class="row list-single">
<div class="col-2"><img src="https://images.gr-assets.com/books/1447303603s/2767052.jpg"/></div>
<div class="col-10">
<h5> The Hunger Games</h5>
Learn
</div>
</div>
<br>
<div class="row list-single">
<div class="col-2"><img src="https://images.gr-assets.com/books/1507396732s/2.jpg"/></div>
<div class="col-10">
<h5>Harry Potter</h5>
Learn
</div>
</div>
<div class="row list-single" id="notAvailable" style="display: none;">
<div class="col-12">
<h5>Sorry, the book has not been added yet</h5>
</div>
</div>
</div>
If you just put this code (in addition to your current code) to the top level of your script. It will be executed as soon as the page loads (technically, as soon as the script loads) and if there is any text in the input field, that text will be used to filter book entries right away.
const term = searchBar.value;
if (term !== '') { // test if the input fields is not empty
const books = document.getElementsByTagName('h5');
let notAvailable = document.getElementById('notAvailable');
let hasResults = false;
Array.from(books).forEach(function(book) {
const title = book.textContent;
if (title.toLowerCase().indexOf(term) != -1) {
book.parentElement.parentElement.style.display = 'flex';
hasResults = true;
} else {
book.parentElement.parentElement.style.display = 'none';
}
});
notAvailable.style.display = hasResults ? 'none' : 'block';
}

memory game how to flip current card with set attribute

I'm making a memory game and trying to flip a card to its image value. when I click on the card it should change the image to the current image in the array but for some reason, it's not working.
JS
var faces = []; //array to store card images
faces[0] = 'images/king-of-diamonds.png';
faces[1] = 'images/king-of-hearts.png';
faces[2] = 'images/queen-of-diamonds.png';
faces[3] = 'images/queen-of-hearts.png';
var cardsInPlay = [];
var checkForMatch = function (cardId) {
if (faces[cardId] === faces[cardId + 1]) {
console.log("You found a match!");
} else {
console.log("Sorry, try again.");
}
}
var flipCard = function (cardId, name) {
document.getElementById('image1')[this].getAttribute("id").src = faces[cardId]
checkForMatch();
}
HTML
<div>
<img onclick="flipCard(1,this)" id="image1" src="images/back.png" alt="Queen of Diamonds">
<img onclick="flipCard(2,this)" id="image1" src="images/back.png" alt="Queen of Hearts">
<img id="image3" src="images/back.png" alt="King of Diamonds">
<img id="image4" src="images/back.png" alt="King of Hearts">
</div>
You should avoid using the same id in different elements. Id is thought to be unique and so you should not have more elements with the same id in the entire page.
At this point you can directly do:
var flipCard = function (cardId, name) {
document.getElementById('image1').src = faces[cardId];
checkForMatch();
}

Javascript / Blockchain.info Websocket API Address Subscription

I am new to bitcoin, Blockchain.info API and javascript, however, i am trying to implement a code that tracks Live Payments notification on a particular bitcoin address. The idea here is... after the user scans the QR image <img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">, and makes payment to the BTC address, 12fMma2J15qre9bZPsX3AerdgWd9Poe9ee, the Div with ID #websocket will instantly display Live (without refreshing the webpage), the amount of Bitcoins Transaferred to the address, thus switching the initial content of the div from monitoring... to the amount transferred Recieved: 0.003 BTC.
I have written a piece of code ... but i'm not sure what i'm missing. Please Help. Thank you.
The code:
<div class="row">
<div class="col-md-4 ">
<img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">
<div id="websocket">
Monitoring Transactions ...
</div>
<script>
var btcs = new WebSocket("12fMma2J15qre9bZPsX3AerdgWd9Poe9ee");
btcs.onopen = function() {
btcs.send(JSON.stringify({"op":"addr_sub", "addr":"12fMma2J15qre9bZPsX3AerdgWd9Poe9ee"}));
};
btcs.onmessage = function (onmsg) {
var response = JSON.parse(onmsg.data);
var getOutputs = response.x.out;
var countOuts = getOutputs.length;
for (i=0; i < countOuts; i++){
var outAdd = response.x.out[i].addr;
var address = "12fMma2J15qre9bZPsX3AerdgWd9Poe9ee";
if (outAdd == address){
var amount =response.x.out[i].value;
var calAmount = Amount / 100000000;
document.getElementById("websocket").innerHTML = "Recieved" + calAmount + "BTC";
}
}
};
</script>
</div>
<div class="col-md-8">
<!-- more html stuff goes here -->
</div>
</div>
I don't see anywhere in the code a connection being made to blockchain's api, so I'm guessing this
var btcs = new WebSocket("12fMma2J15qre9bZPsX3AerdgWd9Poe9ee");
should use the api's address instead of the target bitcoin wallet address.
Probably you need to put wss://ws.blockchain.info/inv while starting a new socket at the place of address.
<div class="row">
<div class="col-md-4 ">
<img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">
<div id="websocket">
Monitoring Transactions ...
</div>
<script>
var btcs = new WebSocket("wss://ws.blockchain.info/inv");
btcs.onopen = function() {
btcs.send(JSON.stringify({"op":"addr_sub", "addr":"12fMma2J15qre9bZPsX3AerdgWd9Poe9ee"}));
};
btcs.onmessage = function (onmsg) {
var response = JSON.parse(onmsg.data);
var getOutputs = response.x.out;
var countOuts = getOutputs.length;
for (i=0; i < countOuts; i++){
var outAdd = response.x.out[i].addr;
var address = "12fMma2J15qre9bZPsX3AerdgWd9Poe9ee";
if (outAdd == address){
var amount =response.x.out[i].value;
var calAmount = Amount / 100000000;
document.getElementById("websocket").innerHTML = "Recieved" + calAmount + "BTC";
}
}
};
</script>
</div>
<div class="col-md-8">
<!-- more html stuff goes here -->
</div>
</div>

Ionic scroll Performance issue

I am developing application in which I have feeds or some timeline. here is my ng-repeat code:
<div ng-repeat="x in feeds" class="fd-feed-card">
<div class="fd-feed-usr-img">
<img ng-src="{{x.user.media[0].small}}" class="fd-img fd-img-br border-style">
</div>
<div class="ft-16 fd-feed-usr-name">
<span><b>{{x.user.name}}</b></span><span class="ft-12 fd-feed-created-time plx prm">{{x.feed.createdTimeStamp | readableTime}}</span>
</div>
<div ng-style="imgStyle">
<img ng-src="{{x.feed.media[0].medium}}" class="fd-img objectcover image-blur">
</div>
<div ng-if="x.feed.total_comments > 0 || x.feed.total_likes >0">
<p class="mll"><span on-tap="openCommentModal(x.feed._id, $index, x.feed)" class="prm" ng-if="x.feed.total_comments > 0">{{x.feed.total_comments}} Comment</span><span ng-if="x.feed.total_likes>0" on-tap="openUserModal(x.feed._id)">{{x.feed.total_likes}} Likes</span>
</p>
</div>
<div class="fd-feed-distance">
<span class="plx prm ft-16">{{x.distance}} <span class="ft-10">mil</span></span>
</div>
</div>
here every feed contains username, userimage and 400*400px image of feed and distance. after this im using ionic infinite scroll like this:
<ion-infinite-scroll on-infinite="getDashboardFeed()" distance="1%" ng-if="!noMoreFeedContent"></ion-infinite-scroll>
in my javascript code, i am calling API with pagination having 5 feeds at a time. here it is my javascript code:
$scope.getDashboardFeed = function(start) {
var _start = start || false;
var params = {}
params.offset = offset;
params.limit = limit;
Posts.getAllFeeds(params).success(function(res) {
if (_start) {
$scope.feeds = [];
}
if (res.data.length < limit) {
$scope.noMoreFeedContent = true;
} else {
$scope.noMoreFeedContent = false;
}
for (var i = 0; i < res.data.length; i++) {
var markerPos = new google.maps.LatLng(res.data[i].feed.location[0], res.data[i].feed.location[1]);
var currentLatLng = new google.maps.LatLng(res.data[i].location.location[0], res.data[i].location.location[1])
var distance = google.maps.geometry.spherical.computeDistanceBetween(markerPos, currentLatLng) * 0.000621371;
res.data[i].distance = distance.toFixed(2);
for (var j = 0; j < res.data[i].feed.likes.length; j++) {
if (uid == res.data[i].feed.likes[j].user) {
res.data[i].isLiked = true;
break;
} else {
res.data[i].isLiked = false;
}
}
$scope.feeds.push(res.data[i]);
}
offset = offset + limit;
if (_start) {
$scope.$broadcast('scroll.refreshComplete');
} else {
$scope.$broadcast('scroll.infiniteScrollComplete');
}
})
.error(function(err) {
})
};
im also calculating distance of every feed based on current location. and checking if i liked the post or not.
Now the problem is when feed is loaded to 25,30 , the scroll becomes laggy in my android . Im also using native scrolling given in this link ,
i have read also more blogs like this
but i didnt get much help. I have to load 1000s of feeds here where every feed contains 400*400px picture.
i also tried collection-repeat. it didnot work either.
Is there any other approach I can try to fix my scroll perfomance?
Anybody can help me with that?
I had same issue, especially when using images in ng-repeat.
Check out my answer here

Categories

Resources