Swap Position of two DIV using ID - javascript

i'm trying to change the position of two DIV'S in jquery, it seems that i may be a little confuse because it is already swapping position, but when it do, it duplicates the field.
i tried using insertBefore and insertAfter.
<div id="before_stops">
<li><span><img src="<?php echo base_url('assets/images/multi_stops.png') ?>" width="18px"height="18px"/></span>
<div class="verticalLine"></div>
<span class="text multi_non_append_stops"></span>
<br><br>
</li>
</div>
<div id="multi_stops">
<span class="text multi">
<li><span>
<img src="<?php echo base_url('assets/images/EndPoint.png')?>" width="18px" height="18px"></span>
<div class="verticalLine"></div>
<br/><br>
</li>
</span>
</div>
Here is my javascript code:
for (var i = 0; i < data.stops.length; i++) {
if(value == "A" || value == "B"){
$('#multi_stops').insertBefore($('#before_stops'));
$('.multi').append('<li><span><img src="' + base_url + 'assets/images/multi_stops.png" width="18px" height="18px"></span><div class="verticalLine"></div>' + data.stops[i].stopDestination + "<br/><br></li>");
}else{
$('#multi_stops').insertAfter($('#before_stops'));
$('.multi').append('<li><span><img src="' + base_url + 'assets/images/multi_stops.png" width="18px" height="18px"></span><div class="verticalLine"></div>' + data.stops[i].stopDestination + "<br/><br></li>");
}
}
what is happening is instead of having a output of
if the value is A or B
it should be
<div id ="multi_stops"></div>
<div id ="before_stops"><div>
but what is happening to me is
<div id ="multi_stops"></div>
<div id ="before_stops"><div>
<div id ="multi_stops"></div>
else if the value is not A or B
it should only be
<div id ="before_stops"></div>
<div id ="multi_stops"><div>
but what is happening is
<div id ="before_stops"></div>
<div id ="multi_stops"><div>
<div id ="multi_stops"></div>
it is duplicating. what am i doing wrong here.

You need to copy the element, insert it after, then delete the first one. Or you would end up with duplicates. You could use jquerys detach method. It removes the object but it keeps the data. Use it like this:
for (var i = 0; i < data.stops.length; i++) {
if (value == "A" || value == "B") {
$('#multi_stops').detach().insertBefore($('#before_stops'));
$('.multi').append('<li><span><img src="' + base_url + 'assets/images/multi_stops.png" width="18px" height="18px"></span><div class="verticalLine"></div>' + data.stops[i].stopDestination + "<br/><br></li>");
} else {
$('#multi_stops').detach().insertAfter($('#before_stops'));
$('.multi').append('<li><span><img src="' + base_url + 'assets/images/multi_stops.png" width="18px" height="18px"></span><div class="verticalLine"></div>' + data.stops[i].stopDestination + "<br/><br></li>");
}
}

Try this:
<div class="holder">
<div id="before_stops">
</div>
<div id="multi_stops">
</div>
</div>
if(value == "A" || value == "B"){
$("#before_stops").appendTo(".holder");
}else{
$("#multi_stops").appendTo(".holder");
}
Live example: https://codepen.io/noelelias/pen/bGbwwBz

Related

Creating simple new parent elements with incrementing class numbers without changing the HTML

I'm trying to create a few elements with class names to have a number on the end that increments by 1 for each new element. E.g. <div class='someClass1'></div>, then <div class='someClass2'></div>, <div class='someClass3'></div>, etc...
However, I can only get the child elements to have incrementing class names, e.g. <span class='0'>here</span>, <span class='1'>here</span>, <span class='2'>here</span>, etc, which is done by changing the inner HTML.
How can I get the parent 'someClass' to have incrementing class numbers? I tried newNode.classList.add("someClass + noAdded"); but returns a syntax error. Thanks for any help here - my code is as follows:
var testy = document.getElementById('testy'); // <div id='testy'></div>
var noAdded = 0;
function addToPage() {
var newNode = document.createElement("div"); // <div></div>
newNode.classList.add("someClass"); // <div class='someClass'></div>
newNode.innerHTML = '<span class="' + noAdded + '">here</span>'; // <span class='0'>here</span>
testy.appendChild(newNode); // <div id='testy'><span class='0'>here</span></div>
noAdded++;
}
addToPage();
addToPage();
addToPage();
Results in:
<div id="testy">
<div class="someClass">
<span class="0">here</span>
</div>
<div class="someClass">
<span class="1">here</span>
</div>
<div class="someClass">
<span class="2">here</span>
</div>
</div>
Concatenate the value of the variable noAdded to the string someClass.
Change
newNode.classList.add("someClass");
To
newNode.classList.add("someClass"+noAdded);
var testy = document.getElementById('testy'); // <div id='testy'></div>
var noAdded = 0;
function addToPage() {
var newNode = document.createElement("div"); // <div></div>
newNode.classList.add("someClass"+noAdded); // <div class='someClass'></div>
newNode.innerHTML = '<span class="' + noAdded + '">here</span>'; // <span class='0'>here</span>
testy.appendChild(newNode); // <div id='testy'><span class='0'>here</span></div>
noAdded++;
}
addToPage();
addToPage();
addToPage();
.someClass0{color:red;}
.someClass1{color:green;}
.someClass2{color:blue;}
<div id="testy">
</div>

Change background of dynamic added elements

I want to change the background of the last added element in the dom. To give you a better look here is the html:
<div class="check-in-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="ticket-img">
<img class="image" src="img/icons/ticket.png">
</span>
</div>
<div class="ui-block-b">
<h4>Inchecken</h4>
<div class="check-in-notification-append"></div>
</div>
</div>
</div>
<div class="douane-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="douane-img">
<img class="douane-img image" src="img/icons/douane.png">
</span>
</div>
<div class="ui-block-b">
<h4>Douane</h4>
<div class="douane-notification-append"></div>
</div>
</div>
</div>
<div class="gate-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="gate-img">
<img class="gate-img image" src="img/icons/gate.png">
</span>
</div>
<div class="ui-block-b">
<h4>Gate</h4>
<div class="gate-notification-append"></div>
</div>
</div>
Where I append the elements to check-in-notification-append, douane-in-notification-append, gate-in-notification-append here a better look at the js file.
$(document).on("pagebeforeshow","#progress",function(){
var incheckHtml = '';
var douaneHtml = '';
var gateHtml = '';
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
var typeOf = info.data[count][5];
if(typeOf === "warning"){
imgPath = 'img/icons/alarm.png';
} else {
imgPath = 'img/icons/alert.png';
}
if (!Array.prototype.last){
Array.prototype.last = function(){
return this[this.length - 1];
};
};
if (category === 'inchecken'){
incheckHtml = incheckHtml + "<div class='notification-item'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
// $('.check-in-wrapper').empty().prepend(incheckHtml);
$('.check-in-notification-append').empty().prepend(incheckHtml);
}
if(category === 'douane'){
douaneHtml = douaneHtml + "<div class='notification-item overlay'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
$('.douane-notification-append').empty().prepend(douaneHtml);
}
if(category === 'gate'){
gateHtml = gateHtml + "<div class='notification-item overlay'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
$('.gate-notification-append').empty().prepend(gateHtml);
}
}
});
But how do I acces the last added element in any category which removes the class "overlay". I'll hope someone could help me out accessing the last added element and removeClass overlay. I have written an .last() function but this will only give me the output of the last object in array...
I think you could achieve this by having some common selector which applies to all the elements that could be affected and using Jquery's last() function.
$(".allMyThings").last().removeClass("overlay");
https://api.jquery.com/last/

JavaScript - Function that Changes content when clicked up or down

I am trying to create a function that when you click up it appends to the div what you want and if you press up again will show what you want again and replace the other data, same for when you press down.
The idea is to have 5 options, the option that it starts on is decided on that users info. So say they are number 3 it will start on number 3 and if you press up it will go to number 2 if you press down it will go to number 4 and show the data with those numbers.
What I am trying to figure out is how can I make this option and then when clicked do what I want it to do.
Idea of what it looks like:
When you press the blue up will go up a page and only show the player that are in diamond 2. and same for the rest
<main>
<div class="panel">
<div class="panel-body"></div>
<div class="league-banner" style="height: 50px;">
<div class="league-number" style="top: 15px; position: relative;">
<div class="league-rank">
III
</div>
<div class="league-buttons">
<img src="img/league/up.png"/>
<a class="sq-btn" href="" style="position: relative; top: -30px;"><img src="img/league/down.png"/></i></a>
</div>
</div>
<span style="color:#57a2dd; font-size: 20px;">DIAMOND 5 </span>
<span style="font-size: 20px;" class="second-banner">Diamond V</span>
<div class="light" style="font-size:20px;">Lee Sin's Redeemers</div>
</div>
<div class="league-top">
<div class="stats-header stats-row">
<div class="table-cell">Rank</div>
<div class="table-cell">Summoner</div>
<div class="table-cell">Emblems</div>
<div class="table-cell">Wins</div>
<div class="table-cell">Losses</div>
<div class="table-cell">Win Rate</div>
<div class="table-cell">Points</div>
</div>
<div class="scroll-league" id="scroll-league">
<?php
if ($league_list){
$entrieszlist = $league_list->entries;
usort($entrieszlist, function($acl,$bcl){
return $bcl->leaguePoints-$acl->leaguePoints;
});
$index = 0;
foreach ($entrieszlist as $datazlistleague){
$playerleagueId = $datazlistleague->playerOrTeamId;
$playerleagueNameSummoner = $datazlistleague->playerOrTeamName;
$playerleagueNameSummonerDivison = $datazlistleague->division;
$playerleagueNameSummonerWins = $datazlistleague->wins;
$playerleagueNameSummonerLosses = $datazlistleague->losses;
$playerleagueNameSummonerLP = $datazlistleague->leaguePoints;
$playerleagueNameSummonerGamesPlayed = $playerleagueNameSummonerWins + $playerleagueNameSummonerLosses;
$playerleagueNameSummonerGamesWinRate = (100/$playerleagueNameSummonerGamesPlayed)*$playerleagueNameSummonerWins ;
$playerleagueNameSummonerLPtarget = $datazlistleague->miniSeries->target;
$playerleagueNameSummonerLPWins = $datazlistleague->miniSeries->wins;
$playerleagueNameSummonerLPLosses = $datazlistleague->miniSeries->losses;
$playerleagueNameSummonerLPProgress = $datazlistleague->miniSeries->progress;
if (isset($datazlistleague->miniSeries)){
$miniSeriesdatayesnodata = 1;
} else {
$miniSeriesdatayesnodata = 2;
}
$summonerData1;
if(isset($playerleagueNameSummoner)) {
$formatedUserName1 = str_replace(" ", "", $playerleagueNameSummoner);
$formatedUserName1 = mb_strtolower($formatedUserName1, 'UTF-8');
$sql1 = 'SELECT * FROM players_data WHERE sum_name = "' . $formatedUserName1.'"';
$result1 = $conn->query($sql1);
if($result1->num_rows > 0) {
while ($row1 = $result1->fetch_assoc()) {
$GLOBALS['summonerData1'] = unserialize($row1['summoner_info']);
}
} else {
storeData($conn, $apiKey, $playerleagueNameSummoner, 'players_data');
header("Refresh:0; url=leaguesprofile1.php?userName=".$_GET['userName']."");
}
} else {
}
$sumiconid1 = $summonerData1->profileIconId;
$index++;
echo '<div class="stats-data stats-row loser" data-ladder_id="'.$playerleagueId.'" data-ladderdivison_id="'.$playerleagueNameSummonerDivison.'" data-promos1or2="'.$miniSeriesdatayesnodata.'">
<div class="table-cell rank">'.$index.'</div>
<div class="table-cell change-selected">
<a href="profile2.php?userName='.$playerleagueNameSummoner .'">
<div style="display: table;">
<div style="display: table-row;">
<div class="table-cell-2">
<div class="summoner-icon" style="background-image: url(http://ddragon.leagueoflegends.com/cdn/6.24.1/img/profileicon/'.$sumiconid1 .'.png);"></div>
</div>
<div class="table-cell-2">'.$playerleagueNameSummoner .'</div>
</div>
</div>
</a>
</div>
<div class="table-cell">
<div style="display: inline-block;" original-title=""> ';
if($datazlistleague->isHotStreak == true){
echo '<img src="img/league/Hot_streak.png"/>';
} else if($datazlistleague->isHotStreak == false){
echo '<img src="img/league/streak_none.png"/>';
}
echo '</div><div style="display: inline-block;" original-title="">';
if($datazlistleague->isFreshBlood == true){
echo '<img src="img/league/Recruit.png"/>';
} else if($datazlistleague->isVeteran == true){
echo '<img src="img/league/Veteran.png"/>';
} else if ($datazlistleague->isFreshBlood == false && $datazlistleague->isVeteran == false){
echo '<img src="img/league/Recruit_none.png"/>';
}
echo '</div>
</div>
<div class="table-cell change-selected">'.$playerleagueNameSummonerWins.'</div>
<div class="table-cell change-selected">'.$playerleagueNameSummonerLosses.'</div>
<div class="table-cell change-selected">'.number_format((float)$playerleagueNameSummonerGamesWinRate, 1, '.', '').'%</div>
<div class="table-cell change-selected">';
echo $playerleagueNameSummonerLP.'LP';
echo '</div>
</div>';
}
}
?>
</div>
</div>
</div>
</main>
CODE - What it should do is depending if the data-attribute called "data-ladderdivison_id" is I then show when page I showen if it is V then show that data on page V but using a up and down button from 1 - 5 to change.
Thanks in advance
You'll need to look at the structure your data is in and determine fairly early on in the script which bit is the "current important" entry point, that would probably be an indexer into an array containing your leagues.
You can do this for example by passing a parameter via the url that you then pickup in the beginning of your script, or initialize to some predefined point (probably 0 for the first league).
// take the ?league=... from the url or set it to 0
$currentLeagueIndex = isset($_GET['league']) ? $_GET['league'] : 0;
then where you're rendering the buttons you can point to the current url with that index plus or minus one.
$hrefPrevious = $currentLeagueIndex-1 > -1 // bounds check for sanity
? 'my-url?league=' . ($currentLeagueIndex-1);
: 'javascript:void()';
$hrefNext = ($currentLeagueIndex+1) < count($allLeagues)
? 'my-url?league=' . ($currentLeagueIndex+1);
: 'javascript:void()';

javascript loop thought bootstrap

I have a simple bootstrap page I need to load JSON data into it:
This is my script:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var tweets = JSON.parse(xhr.responseText);
var tweet = ' <div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">';
var name = ' <h4 class="card-title">';
var photo = ' <div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">';
for (var i = 0; i < tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
document.getElementById('photo').innerHTML = photo;
document.getElementById('name').innerHTML = name;
document.getElementById('tweet').innerHTML = tweet;
// close all html tags
}
}
};
xhr.open('GET', 'empdata.json');
xhr.send();
And this is my HTML:
<div class="container">
<div class="card">
<div class="card-header">
<div class="row">
<div id="photo">
<!-- here where the pic goes ! -->
</div>
<div id="name">
<!-- here where the name goes ! -->
</div>
</div>
<div class="card-block row">
<div id="tweet">
<!-- here where the tweet goes ! -->
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-block row">
<div id="tweet"> </div>
</div>
It loops correctly through all JSON data, but it displays all the pictures first then the names and finally the tweets separately. think the problem is related to the mechanism I follow in the loop.
I think you mean to do this. It can be much simpler but without changing your html I would do this:
var container = document.querySelector(".container");
for (var i=0; i<tweets.length; i += 1) {
var name = ' <h4 class="card-title">';
name += tweets[i].name;
name += '</h4> </div>';
var tweet = '<div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">'
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
var photo ='<div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">'
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
container.innerHTML+='<div class="card"><div class="card-header">'+
photo+name+tweet+'</div></div>';
}
EDITED Try set innerText outside from the loop
for (var i=0; i<tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
...
photo += tweets[i].pic;
photo += '"></div></div>';
}
document.getElementById('name').innerHTML = name;
document.getElementById('photo').innerHTML = photo;

jQuery - Passing data from a jQuery function to a specific div?

I'm trying to pass data from a function to a specific div, but I can't seem to be able to get this to work. I'm making a gallery viewer and I just want to pass the counter that I use to show the pictures and the total number of files for each gallery in the page.
Here is the code:
jQuery
$(document).ready(function () {
$('.photoset').each(function () {
$(this).data('counter', 0);
$items = $(this).find('img')
$(this).data('numItems', $items.length);
});
var showCurrent = function (photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.fadeOut();
$items.eq(itemToShow).fadeIn();
};
$('.photoset').on('click', function (e) {
e.stopPropagation();
var photoset = $(this);
var pWidth = photoset.innerWidth();
var pOffset = photoset.offset();
var x = e.pageX - pOffset.left;
if (pWidth / 2 > x) {
photoset.data('counter', photoset.data('counter') - 1);
if (photoset.data('counter') < 0)
photoset.data('counter', photoset.data('numItems') - 1);
showCurrent(photoset);
} else {
photoset.data('counter', photoset.data('counter') + 1);
if (photoset.data('counter') > photoset.data('numItems') - 1)
photoset.data('counter', 0);
showCurrent(photoset);
}
$(this).text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'))
});
});
Html Razor
<div class="container">
#{ var i = 10; }
#foreach (var item in Model)
{
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
<br />
#Html.DisplayFor(modelitem => item.NomeGaleria)
<br />
</div>
</div>
<div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
<div class="row">
<div class="photoset center-block">
#{ var item2 = item.FilePaths;}
#for (var k = 0; k < Enumerable.Count(item2); k++)
{
<br />
<img src="~/images/#Html.DisplayFor(modelItem2 => item2[k].FileName)" style="#(k != 0 ? "display: none" : "" ) " />
<br />
}
</div>
</div>
}
</div>
So I'm trying to use this code
$(this).text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'))
to pass the data to the "nav-informer" div, but it just won't work. Does anyone knows what to do in this case? Sorry if this is a dumb question, I'm very new to jQuery.
UPDATE
Here is the rendered HTML page:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
<br />
Galeria Um
<br />
</div>
</div>
<div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
<div class="row">
<div class="photoset center-block">
<br />
<img src="/images/572fdd6b-13eb-48d2-8940-23da73e056c0.JPG" style=" " />
<br />
<br />
<img src="/images/018a55be-a8a7-4412-8415-1678d01eb6a2.JPG" style="display: none " />
<br />
<br />
<img src="/images/e5b0bdcb-d517-49a5-818b-245d46c0a0d9.JPG" style="display: none " />
<br />
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
<br />
Galeria Dois
<br />
</div>
</div>
<div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
<div class="row">
<div class="photoset center-block">
<br />
<img src="/images/fdc2e9fd-978a-4150-87af-483e34f68798.JPG" style=" " />
<br />
<br />
<img src="/images/b17d169d-e5ed-45cd-9901-1d9dc294c873.JPG" style="display: none " />
<br />
<br />
<img src="/images/3ad1ae20-7102-4d69-b658-7b3d8cbfb9e8.JPG" style="display: none " />
<br />
<br />
<img src="/images/4ef03a84-da00-4f93-b3a2-839ac2ec9ac2.JPG" style="display: none " />
<br />
</div>
</div>
So, since you're new to jQuery, the use of $(this) basically means "the element that I've started the process with" which in your case is .photoset. So $(this) = $('.photoset')
If you want to make that line of text go into your .nav-informer div, you need to change $(this) to $('.nav-informer')
$('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
UPDATE
So it seems you need to traverse through the hierarchy. Is each 'gallery' a .container? If so, try this:
$(this).closest('.container').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
.closest() traverses up through the hierarchy trying to find the closest parent of the element you start with. (in our case $(this)).
'.find()' does the opposite, it goes down through the hierarchy to find the first instance of the element in question from the point before.
Add them together and what I like to do is .closest() to the parent of the element you're trying to find and .find() the element after that. I feel like doing .parents(), .children() and .siblings() gets messy.
UPDATE 2
Alright, I see now - The way you're exporting each gallery may get a bit dicey eventually, and if possible, I would suggest containing your gallery and informer into the same container, but if you're going to leave it like this, try this:
$(this).closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
So, using .parent() will traverse only a single parent, where if you needed to go farther up, you can use .parents() (with an S) or my favorite .closest(). Then, once you reach the level you need to go, you can use .siblings(), or in our case, since your .nav-informer is always in the .row before your .photoset, you need to use .prev(). This will select the div written directly before the div you are currently, at the same level.
Check This Fiddle to see a quick example.

Categories

Resources