Passing multiple values in Javascript OnClick, using those values in specific ways - javascript

While I've done some Javascript coding, I consider myself a more novice, Frankenstein-type coder, basically cutting and pasting with trial and error to see if I can get something to work...just a heads up on my honest assessment of my experience level.
I've got a unique thing I'm developing for, and hoping to get some help with Javascript. Here's what I'm trying / need to do: for a webpage based kiosk presentation, I'm using one HTML webpage, but with multiple sections whose visibility toggles on/off based on a Javascript I currently have that works fine. (I don't want to / can't use regular HTML pages with links because of how it ends up running).
The only problem with the above issue is that there's no easy way to create a 'back' or 'previous page' link for an end page that may have multiple ways to get to it. It won't 'know' where the user came from.
So here's what I'd like to do: pass 2 variables through my OnClick javascript function, the DIV name that needs to toggle on/off ... AND a 2nd variable of the current visible DIV name so that the next DIV that toggles on can 'remember' what the previous (and now invisible) DIV was so that there can be an accurate 'back' button.
Here's some sample code:
Each DIV section that turns on an off is setup like this:
<div id="sectionName" class="content">
</div>
These DIVs have buttons/links that are setup like this:
These run a Javacript:
function toggleVisibility(selectedTab) {
var content = document.getElementsByClassName('content');
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
So what I'm hoping is that there is a way to do something like this:
So that when that is clicked, the next DIV that turns on could also include a Javascript generated link based on that passed variable, something like:
Previous<br>Menu
I'm aware that Javascript toggling of DIVs on and off may not allow the generation of a dynamic Javascript link like the one I'm describing above, so I'm throwing this out there for some help from other, far more experienced programmers. Ideally, I'd like to try and fit everything into what I've created so far, so I don't have to start over from scratch. Any ideas?
Please reference this sample page:
www.gs3creative.com/test/

You could use location hashes (mypage.html#mydivid) and then use history.back() to handle 'back' navigation.
To stitch up the div's showing on the correct hash value....
var oldHash = '';
// fires when the hash changes
function hash_changed() {
var hash = location.hash.replace('#', ''); // get the div ID
var div = document.getElementById(hash); // find the content div on the page
var allDivs = document.getElementByClassName('content'); // get all of the content divs
// hide all the content divs
for (var i = 0; i < allDivs.length; i++) {
var thisDiv = allDivs[i];
thisDiv.style.display = 'none';
}
// only show the right one
div.style.display = 'block';
}
// this triggers the event
setInterval(function() {
// if the hash has changed, fire the function
if (oldHash != location.hash) {
oldHash = location.hash;
hash_changed();
}
}, 100); // call every 100 ms so that there is no lag
So if you set the navigation to 'mypage.html#sectionName' it would hide all other div's of the class 'content' and then only show the div with the ID of 'sectionName'.

An easy solution for me would be to render two content pages on a HTML page and show and hide content when needed from a onlick handler via javascript in your CSS add a class:
function showDiv() {
document.getElementById("theObject").className = "visible";
}
CSS:
// Switch between the content adding the classes and removing the old class
.visible{
display:none;
}
.show{
display:block;
}
Another solution using sessions "php" via javascript to hold the variables with in statements.
<?php if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['user_is where_variable'] = "im on page div 1";
}
This could also be done through js anyways.
javascript have a conditional statement using your $_SESSION vars;
if (variable == "im on page div 1" ){
// your functions
}else if ( variable == "im on page div 1"){
// another function
}
Create your click handler to update the variables in the session.

Related

Refresh div during JQuery update

I have a html file with many div. Beside this I have a JQuery file too which run an AJAX request in every 30 seconds. In my JQuery If a condition met and the jQuery reloded 3 times I want to update my div-s. I tried to add a div, but it does not appear just when I reload my whole page. If I set to remove my div and not add, the JQuery removes my div, so it is very odd for me, because just the .add or .append or .html do not working. furthermore I set a class with invisibility too, and I also set that when the condition met the jQuery file remove the invisibility class, but the div do not want to appear. I am trying to create a sample code.
My html
<div class="row">
<div id="myclass" class= "invisible" >
<div <p> Please appear for me!<p></div>
</div>
</div>
My JQuery:
if (condition) {
$('#myclass').removeClass('invisible');
if (n >= 2) {
$('#myclass').addClass('invisible');
}
}
The main point is, If the conditions met the class not removes just When I reload my page. In the jQuery file the n is equal with the times when the AJAX reloaded with setInterval. My question is why my div not appear just when I reload my whole page? Also why remove without reload?
Thank you in advance the answers!
removeClass and addClass perfectly work. at first, you can check if you jQuery works, just try to write you script (with ".append",".html",".insertAfter") directly in browser console, else you can add some console.log in your code, when you change invisibility like:
console.log('removeClass');
$('#myclass').removeClass('invisible');
if (n >= 2) {
console.log('addClass');
$('#myclass').addClass('invisible');
}
for update some div content, you can use simple function for it. like -
call self page in get request, and replace div content.
function reloadMyDiv(selector){
var element = $(selector);
if(element.length===1){
$.get(window.location.href,{},function(response){
var new_page = $('<div></div>').append(response);
var new_element = new_page.find(selector);
if(new_element.length===1){
element.html( new_element.html() );
console.log('update');
}else{
console.log('need contains only one element, '+new_element.length+' found!');
}
});
}else{
console.log('need contains only one element, '+element.length+' found!')
}
};
and if you more _ not use your interval, is good practice for clear it.
var n = 0;
var myInterval = setInterval(function(){ myFunction() },30*1000);
function myFunction(){
n+=1;
//do, what you want to do
if(n>2){
clearInterval(myInterval);
}
}

jQuery Hide/Show DIV on change of anchor text

I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?
What I have tried till now but not working:
$(document).ready(function(){
$(".phone").hide();
var idSample = window.location.href.split("#");
var id = "#"+idSample[1];
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/
I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!
You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....
Example:
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
if(hash == "#first") {
// Hide element
} else {
// Show element
}
}
But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...
You can simply use a substring on your location.hash for get your hash tag
$(document).ready(function(){
$(".phone").hide();
var id = window.location.hash.substr(1);
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

jQuery JavaScript : How to keep track of actions done by users?

I have a webpage with images.
A user can click on images to show() or hyde() these images.
Sometimes, the user opens a popup to watch a video.
Then the code hide() all elements previously opened.
When the user closes the video, i need to know which elements was previously opened in order to show only them.
What is the best way to do that ?
What i've done :
I've created an array and i push images names into it.
var arr_popup_open = [];
Then, this function is called when user open a popup and hide all elements :
function toggleAllPopup() {
if( $('#popup_micro_1').is(":visible"))
{
$('#popup_micro_1').hide();
arr_popup_open.push('#popup_micro_1');
}
if( $('#popup_micro_2').is(":visible"))
{
$('#popup_micro_2').hide();
arr_popup_open.push('#popup_micro_2');
}
if( $('#popup_micro_3').is(":visible"))
{
$('#popup_micro_3').hide();
arr_popup_open.push('#popup_micro_3');
}
}
// and so on ... I have 7 images so it seems it's not very well optimized
When i need to show only images previously opened, i execute this code, a loop to show() elements in array.
$('#close_pop_up').click(function() {
for(var i= 0; i < arr_popup_open.length; i++)
{
$(arr_popup_open[i]).show();
}
});
What do you think about that ? Is there a better way to to do it ?
There are a few ways you could go about this with jQuery. Your way should work, but if you want to reduce the amount of code you could do something like:
var visibleDivs = $('div:visible', '#ContainerDiv');
Alternatively you could add a specific class to all visible elements when you show them and use:
var visibleDivs = $('.someClassName');
When hiding them due to your popup, you can store the list in the data of any element. In this case, putting it on #close_pop_up might make sense:
visibleDivs.hide();
$('#close_pop_up').data('myDivs', visibleDivs);
When you want to show them again in your click function:
$('#close_pop_up').click(function() {
$(this).data('myDivs').show();
});
Looks fine to me. Just remember to clear arr_popup_open in the start of the toggleopen function.
The alternative you could do if you really wanted is to keep the information of what is open or closed in Javascript variables that get updated when you open and close things. This way you don't need to depend on complex things such as is(:visible)

If all overlays closed, then execute function

I have a button on a banner at the top of my page that launches several yui2 overlays on to the screen. Each overlay has a close button on it (which just changes the visibility to hidden so it can be reused). After the overlays are launched, there is also a button on the banner that appears will close all overlays if clicked.
This gives the use the option to close all or close each one individually. This is what i am stuck on:
If the user closes an individual overlay, after I close the overlay, I want to check if any other overlay is still open. If they happen to have closed all of them individually, then I need to revert the banner at the top and remove the "close all button".
I can search for all overlays by doing a:
var elements = YAHOO.util.Dom.getElementsByClassName('test');
I cant think of the logic I would need to do to go through that array each time they close an overlay to see all of them are set to visibility if hidden. If so, then execute a function. If there is still any overlays visible on the page, then do nothing.
This is the answer I came up with. Just not sure if it is correct.
var elements = document.getElementsByClassName('test');
var visiblecounter = 0;
for (var i = 0; i < elements.length; i++) {
if(elements[i].style.visibility!='hidden'){
alert("not hidden");
visiblecounter ++;
}
}
​
if(visiblecounter > 0){
alert("all overlays are closed individually. you can remove close all button");
}
You mention you are reusing those overlays so since you are pooling the overlays for reuse, I assume you have them in an array or something like that. Instead of checking the DOM (which is always expensive) to see if they are visible or not, loop through the array of overlays checking the visible attribute, like:
var anyVisible = false;
for (i = 0; i < myOverlays.length; i+=1) {
anyVisible |= myOverlays[i].cfg.getProperty("visible");
}
If any of them are visible, disable the button.
I am not sure I get the question, but I will try my best to help. Here are some things I would do. I also define an active class, so my HTML elements would be written as this:
<div class="john active"></div>
and in my css I would write.
.john {display: none};
.active {display: block};
So by default the object is hidden! But when you append the "active" class to it, it appears on the screen. So now we can do the following wizardry.
$(".hideButton").click(function() {
$(this).removeClass("active");
});
If I want to hide all the other objects, assuming that they have the same parent in the DOM
$(".hideOthersButton").click(function() {
$(this).siblings().removeClass("active");
});
if I want to hide all objects that share the same parent.
$(".hideEverything").click(function() {
$(".parent").children().removeClass("active");
});
I hope this helps! let me know if you need more help. The solution uses Jquery but you can repurpose the logic for anything else.

Categories

Resources