Passing data among different HTML pages - javascript

I'm new to PHP and very lost.
I'm working with HTML5, CSS3, jQuery and Bootstrap 4.
I have a total of 4 HTML pages on my website. In the first page there are 4 squares with text (let's say A, B, C and D), user selects one of those squares and then presses the "Next" button. On click of this "next" user is taken to page 2 but this page needs to be updated according to user's selection in page 1 (A, B, C or D). And similarly data from page 2 and page 1 needs to be taken to page 3.
I read about doing it via URLs, AJAX, PHP sessions and a few more things, but since I'm new at this I'm very confused.
Please guide as to how can I pass data among different pages?
EDIT: I've not used forms.

There method depends on the purpose, this is one of the fundamental concepts and components in web development.
If you want to store or record your users interaction (for e-commerce, or social networking purposes) you will need the data to be passed to the server at some point (maybe after using a local storage object), there are 2 commonly used mechanisms PHP gives us to pass data from the client side to server side: $_GET & $_POST through a HTML from, and these can persist used cookies or sessions
If the data passed between pages is never going to provide any purpose for the site's function, then the local storage object may be used, the local storage object is particularly useful when large amounts of data may be stored on the users client, rather than fetching this expensive resource per request, to enhance user experience and minimise server load

You can do this with use of localstorage
First Page: (first.html)
localStorage.setItem("square_first", "A");
Second Page: (second.html)
localStorage.getItem("square_first");

You can use local storage following example will definitely help you.
on HTML page 1:
window.onload = function() {
var sqa = prompt("square: ","A");
localStorage.setItem("SQA",sqa);
}
On HTML page 2:
window.onload = alert(localStorage.getItem("SQA"));
You can use cookies but storage is better option as page request is not sent to server.

<html>
<head>
<title>Passing data among different HTML pages</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>
<body>
<div>
<p>Section-A</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<input type="hidden" name="dataA" id="dataA" value="sample data A"/>
<button class="send_data" value="A">Next</button>
</div>
<div>
<p>Section-B</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<input type="hidden" name="dataB" id="dataB" value="sample data B"/>
<button class="send_data" value="B">Next</button>
</div>
<div>
<p>Section-C</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<input type="hidden" name="dataC" id="dataC" value="sample data C"/>
<button class="send_data" value="C">Next</button>
</div>
<div>
<p>Section-D</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<input type="hidden" name="dataD" id="dataD" value="sample data D"/>
<button class="send_data" value="D">Next</button>
</div>
</body>
</html>
<script>
$(document).ready(function() {
 
  $(".send_data").click(function(event){
  
var url="";
let sec = $(this).prop("value");
let data = $('#data'+sec).val();
if (sec=="A"){
url = 'demoA.html';
} else if (sec=="B"){
url = 'demoA.html';
}
else if (sec=="C"){
url = 'demoA.html';
}
else if (sec=="D"){
url = 'demoA.html';
}
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="data" value="'+data+'" />' +
'</form>');
$('body').append(form);
form.submit();
  });
  
});
</script>

Related

Is it possible to change an attribute value from another html file?

So I have a website right now and I want to change the aria-expanded value of an exapandable paragraph in another page when I press an anchor element in the main page. What will I need to change in my main.html so i can somehow change the aria-expanded value on the help.html file?
main.html
<a href="help">
<h2>Returns Policy</h2>
</a>
help.html
<div class="accordion-item">
<button id="accordion-button-3" aria-expanded="false"><span
class="accordion-title">Returns Policy</span><span
class="icon" aria-hidden="true"></span></button>
<div class="accordion-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Elementum sagittis vitae et
leo duis ut. Ut tortor pretium viverra suspendisse potenti.
</p>
</div>
</div>
//and this is the script used to expand the paragraph
const items = document.querySelectorAll(".accordion button");
function toggleAccordion() {
const itemToggle = this.getAttribute('aria-expanded');
for (i = 0; i < items.length; i++) {
items[i].setAttribute('aria-expanded', 'false');
}
if (itemToggle == 'false') {
this.setAttribute('aria-expanded', 'true');
}
}
items.forEach(item => item.addEventListener('click', toggleAccordion));
your button id is "accordion-button-3" so in querySeletorAll you need "#accordion-button-3"
const items = document.querySelectorAll("#accordion-button-3");

How can I filter an array with multiple conditions in JavaScript? [duplicate]

This question already has answers here:
javascript filter array multiple conditions
(27 answers)
Closed 1 year ago.
This is my problem:
I have a dropdown menu on my page where the user can click on various menus with each have 3 options. I want to show only the cars which fit the options that were clicked (I have provided part of my HTML code, I hope this will suffice)
Brands:
option 1 = all brands;
option 2 = Seat;
option 3 = Skoda;
Price:
option 1 = all prices;
option 2 = under 35000;
option 3 = over 35000;
Type:
option 1 = all types;
option 2 = new;
option 3 = used;
//JSON data snippet
{
"vehicle": [{
"id": 1,
"brand": "Seat",
"name": "Seat Ibiza 5V",
"price": "12000,00 €",
"description_small": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.",
"description": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
"images": [
"ibiza_1.jpg",
"ibiza_2.jpg",
"ibiza_3.jpg"
],
"detail": {
"vehicleStand": "Unfallfrei",
"origin": "Deutschland",
"mileage": "120.000km",
"displacement": "1.198 cm³",
"power": "69ps",
"fuelType": "Benzin",
"consumption": [
"Kombiniert: ca. 3.4l/100km",
"Inneerorts: ca. 5.1l/100km",
"Außerorts: ca. 4.5l/100km"
],
"seats": 5,
"doors": "2/3",
"transmission": "Schaltgetriebe",
"pullutionClass": "Euro 5",
"environmentalBadge": "Grün",
"initialRegistration": "10/2013",
"vehicleOwner": 1
}
},]
};
//JSON data end. the JSON has 4 more "vehicles" in it
// the whole JSON data is pushed into this array, but I thought that wasn"t relevant for my problem so I didn"t include it
allCars is a global array my JSON data was pushed into
In theory I know that I have to iterate over allCars with a for loop and inside it ask with multiple if wether a condition is true and if it is, check for the second and third conditions and pushing the result into filteredCars but I'm struggling where to put what exactly.
What I am also worried about is how I can properly check for the price, because to me it looks like the price inside the JSON is a string and not a number?
I'll be thankful for any input and will try to figure out how to update my question if I can achieve what I need (oh annd please try to explain in really simple terms, I am often easily confused as you might notice^^)
let allCars = [];
function getSelectedOptions() {
var brand = document.getElementById('brands').value;
var price = document.getElementById('prices').value;
var type = document.getElementById('types').value;
carsFilter(brand, price, type);
}
function carsFilter(brand, price, type) {
var filteredCars = [];
for (i = 0; i < allCars.length; i++) {
if (brand == 'all' || brand == allCars[i].brand) {
if (price == 'allPrices' || price == allCars[i].price) {
if (type == 'allTypes' || type == allCars[i].vehicleOwner) {
}
}
}
filteredCars.push(allCars[i].brand);
filteredCars.push(allCars[i].price);
filteredCars.push(allCars[i].vehicleOwner);
}
showCars(filteredCars);
//a function which will then show the result cars I get out of the filter
}
<!DOCTYPE html>
<label for="brands">Brands</label>
<select id="brands" name="carBrands">
<option value="all">All</option>
<option value="seat">Seat</option>
<option value="skoda">Škoda</option>
</select>
<label for="prices">Prices</label>
<select id="prices" name="carPrices">
<option value="allPrices">All</option>
<option value="underPrice">under 35000,00</option>
<option value="overPrice">over 35000,00</option>
</select>
<label for="types">New and used cars</label>
<select id="types" name="carTypes">
<option value="allTypes">All</option>
<option value=0>New</option>
<option value=1>Usedt</option>
</select>
Assuming your data set contains all cars with some properties, ready for filtering.
The pull downs contains only for wanted parts a value for all just an empty string. This information is not needed for filtering.
By submitting the formular, you need to collect the options, assign the value to the corresponding variables, like brand and if not an empty string add a predefined function, like
brandFn = o => o.brand === brand
^ content of pull down
^ property of an item
^ item/object
to an array of functions fns.
The filtering works then with Array#filter and Array#every:
result = data.filter(o => fns.every(fn => fn(o)));
For filtering numerical values add the number without formatting and currency and select the function with an object, like
pricesFns = {
under: o => o.price < 35000,
over: o => o.price >= 35000
}
Add one of the function, depending on selection to fns array.

Javascript Content Multiple Sliders Same Page

I have a question, if someone can help will be greatly appreciated as I've been trying and trying with no success.
http://samiconcepts.com/rise-sports2
In this link, scroll a little down and you'll see 4 video content sliders (these sliders are controlled via the dots. You click dot, slide changes).
Now, I duplicated the HTML for the 4 sliders, but ONLY the first slider works when I click the dots, not the second, third or fourth. I am thinking that the Javascript is only allowing for 1 slider to work on the page at a time.
How can I have it so that all the sliders work? (might need JS/HTML tweaking)?
I am posting code below. Thank you for your consideration to help.
Javascript
// vars
'use strict'
var testim = document.getElementById("testim"),
testimDots = Array.prototype.slice.call(document.getElementById("testim-dots").children),
testimContent = Array.prototype.slice.call(document.getElementById("testim-content").children),
testimLeftArrow = document.getElementById("left-arrow"),
testimRightArrow = document.getElementById("right-arrow"),
currentSlide = 0,
currentActive = 0,
testimTimer,
touchStartPos,
touchEndPos,
touchPosDiff,
ignoreTouch = 30;
;
window.onload = function() {
// Testim Script
function playSlide(slide) {
for (var k = 0; k < testimDots.length; k++) {
testimContent[k].classList.remove("active");
testimContent[k].classList.remove("inactive");
testimDots[k].classList.remove("active");
}
if (slide < 0) {
slide = currentSlide = testimContent.length-1;
}
if (slide > testimContent.length - 1) {
slide = currentSlide = 0;
}
if (currentActive != currentSlide) {
testimContent[currentActive].classList.add("inactive");
}
testimContent[slide].classList.add("active");
testimDots[slide].classList.add("active");
currentActive = currentSlide;
clearTimeout(testimTimer);
testimTimer = setTimeout(function() {
playSlide(currentSlide += 1);
}, testimSpeed)
}
testimLeftArrow.addEventListener("click", function() {
playSlide(currentSlide -= 1);
})
testimRightArrow.addEventListener("click", function() {
playSlide(currentSlide += 1);
})
for (var l = 0; l < testimDots.length; l++) {
testimDots[l].addEventListener("click", function() {
playSlide(currentSlide = testimDots.indexOf(this));
})
}
playSlide(currentSlide);
// keyboard shortcuts
document.addEventListener("keyup", function(e) {
switch (e.keyCode) {
case 37:
testimLeftArrow.click();
break;
case 39:
testimRightArrow.click();
break;
case 39:
testimRightArrow.click();
break;
default:
break;
}
})
testim.addEventListener("touchstart", function(e) {
touchStartPos = e.changedTouches[0].clientX;
})
testim.addEventListener("touchend", function(e) {
touchEndPos = e.changedTouches[0].clientX;
touchPosDiff = touchStartPos - touchEndPos;
console.log(touchPosDiff);
console.log(touchStartPos);
console.log(touchEndPos);
if (touchPosDiff > 0 + ignoreTouch) {
testimLeftArrow.click();
} else if (touchPosDiff < 0 - ignoreTouch) {
testimRightArrow.click();
} else {
return;
}
})
}
HTML
<section id="testim" class="testim">
<div class="wrap">
<span id="right-arrow" class="arrow right fa fa-chevron-right"></span>
<span id="left-arrow" class="arrow left fa fa-chevron-left "></span>
<ul id="testim-dots" class="dots">
<li class="dot active"></li>
<li class="dot"></li>
<li class="dot"></li>
<li class="dot"></li>
</ul>
<div id="testim-content" class="cont">
<div class="active">
<a class="js-rytl--link" href="https://www.youtube.com/watch?v=Rb0UmrCXxVA"><img class="video1 play" src="/images-rise/vi.jpg"></a><br>
<div class="bla"> <div class="title1-1S">VIDEO 1: </div>
<div class="title1-2S">SPEED TRAINING</div></div>
<p class="reviewsText1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
</div>
<div>
<a class="js-rytl--link" href="https://www.youtube.com/watch?v=Rb0UmrCXxVA"><img class="video1 play" src="/images-rise/vi.jpg"></a><br>
<div class="bla"> <div class="title1-1S">VIDEO 2: </div>
<div class="title1-2S">TRAINING</div></div>
<p class="reviewsText1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
</div>
<div>
<a class="js-rytl--link" href="https://www.youtube.com/watch?v=Rb0UmrCXxVA"><img class="video1 play" src="/images-rise/vi.jpg"></a><br>
<div class="bla"> <div class="title1-1S">VIDEO 3: </div>
<div class="title1-2S">TRAINING</div></div>
<p class="reviewsText1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
</div>
<div>
<a class="js-rytl--link" href="https://www.youtube.com/watch?v=Rb0UmrCXxVA"><img class="video1 play" src="/images-rise/vi.jpg"></a><br>
<div class="bla"> <div class="title1-1S">VIDEO 4: </div>
<div class="title1-2S">TRAINING</div></div>
<p class="reviewsText1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
</div>
</DIV>
</DIV>
</section>

URL anchor hash, then open a tab using another id via URL

I need a URL parameter to select a section via the hash ID (#features) and then open tab #2 within that section (Tab 1 is open by default). I want to use index.html#features and then once it has located that section, open tab #2 (#tab2).
My js below looks for the hash in the URL, if the hash is shown, trigger a click effect for the hash. I was trying to use index.html#tab2, but it won't move down to that #features section and so I'm not sure how to solve this.
The #features section is near the bottom of the page, so I need to first locate this section and then open the 2nd tab.
JS Fiddle
<article id="features">
<div class="tab-wrapper">
<ul class="tab-wrapper__tab-list" role="tablist">
<li role="presentation">
Tab One
</li>
<li role="presentation">
Tab Two
</li>
<li role="presentation">
Tab Three
</li>
</ul>
<div id="tab1" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Lorem ipsum dolor sit amet, nam an purto autem contentiones. Cum solet verear petentium ut, an incorrupte interesset sit, eu sea dicant suscipit definiebas. Ut illum habemus sententiae sea, nec nibh accusata an. Tempor dissentias ea nam. Utinam volutpat sed at, dicta errem cu est.</p>
</div>
</div>
<div id="tab2" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Vel zril putent incorrupte ei. Cu tation veniam euripidis vel, diceret minimum deserunt an ius. Eam ex probatus laboramus, cum ad noluisse suscipit, everti accusata id eam. Ius et commune recusabo, id munere alterum mei. Rebum oratio malorum usu te, no feugait inciderint eos. Eum viderer deseruisse instructior at. Nusquam expetenda eam et.</p>
</div>
</div>
<div id="tab3" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Tacimates consetetur his eu. Amet persecuti an eum, ne facete audiam mei. Pri et alia urbanitas, dicunt tacimates eos eu. Ut sit inani urbanitas. Has in equidem atomorum accommodare. Te vim decore cetero intellegebat. Saepe timeam posidonium pro te, nulla insolens adipisci ne vis.</p>
</div>
</div>
</div>
</article>
<script>
$(function () {
var hash = $.trim(window.location.hash);
if (hash) $('.tab-wrapper__tab-list a[href$="'+ hash +'"]').trigger('click');
});
</script>
Have you tried scrolling to the tab button with #tab2 in the URL? This would solve your problem with scrolling down to the features section, as the #tab2 element is on top of the features section.
A JSFiddle runs in an iframe and you need to provide the hash inside the link of the iframe. A workaround for this is just setting the hash with JavaScript. If you set window.location.hash = "tab2"; as the first line in your script section, it scrolls down and displays the second tab.
If you insist on scrolling to the #features element, you can realize that pretty easy with JavaScript. This allows you also to create an animated scroll down to the section. See this answer for more information about that: https://stackoverflow.com/a/16475234/3233827

How to add a class to a parent element based on the child's class using jQuery

I'm creating a standard jQuery image slideshow, but I need to add a certain class to a container div, based on which slide is currently showing.
I'm using Flexslider which helpfully gives the current slide a class of 'flex-active-slide'. What I'd like to do is to use that class combined with a unique class to select the active slide (i.e. '.heating-slide.flex-active-slide).
I'd then like to have jQuery apply an additional class to the containing div (.image-slider.full-width), based on which slide is currently showing.
For example:
If the heating slide is showing, I'd like to apply a class of .heating-container to the .image-slider.full-width div.
If the cooling slide is showing, I'd like to apply a class of .cooling-container
And so on
Here's my code:
<div class="image-slider full-width">
<div class="image-slider-container">
<div class="flexslider wide">
<ul class="slides">
<li class="cooling-slide">
<img src="/assets/images/image-slider/slides/cooling-slide.jpg" />
<div class="flex-caption">
<h2 class="">Cooling</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</p>
<a class="button" href="#">Find out more</a>
</div>
</li>
<li class="heating-slide">
<img src="/assets/images/image-slider/slides/heating-slide.jpg" />
<div class="flex-caption">
<h2 class="">Heating</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</p>
<a class="button" href="#">Find out more</a>
</div>
</li>
<li class="ventilation-slide">
<img src="/assets/images/image-slider/slides/ventilation-slide.jpg" />
<div class="flex-caption">
<h2 class="">Ventilation</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</p>
<a class="button" href="#">Find out more</a>
</div>
</li>
</ul>
</div>
</div>
</div>
And here's my poor attempt at writing the required code:
<script type="text/javascript" >
$(document).ready(function () {
$(".heating-slide.flex-active-slide") SOMETHING HERE (".image-slider.full-width").addClass("heating-container");
});
</script>
Any help you can offer will be appreciated!
Update
I wasn't taking into account the other class that was on the element, also made it remove the previously added class so you don't end up with all of them on there:
$(function() {
function setContainer() {
var activeSlide = $(".flex-active-slide");
var activeSlideClass = activeSlide.attr('class')
.replace('flex-active-slide', '')
.replace("-slide", "-container")
var slider = activeSlide.closest(".image-slider.full-width");
var latestClass = slider.data("latest-class");
if (latestClass) {
slider.removeClass(latestClass);
}
slider.addClass(activeSlideClass)
.data("latest-class", activeSlideClass);
}
$('.flexslider').flexslider({
animation: "fade",
controlsContainer: ".flex-container",
animationSpeed: 800, //Integer: Set the speed of animations, in milliseconds
slideshowSpeed: 10000, //Integer: Set the speed of the slideshow cycling, in milliseconds
after: function() { setContainer(); }
});
setContainer();
});
You should be able to paste that into your code as is instead of the existing flexslider binding.
Working Fiddle - http://jsfiddle.net/xt4Ym/3/

Categories

Resources