Help with JS return statement - javascript

this is probably an easy one, but I am new to JavaScript.
When I click on a tab which has a special id, I want that id saved in a variable. So far, so good. But if I click on a other button I want that button to work with that previous id oft he tab. How am I using the return statement correctly?
Thanks!

// 0 = no tab
var myTabID = 0
function doNewTab(newTabID)
{
// If the tab has not been set
if(myTabID <> 0){
// Do whatever you want with the tab ID in here
alert(myTabID);
}
// Set new tab ID
myTabID = newTabID;
}
Then in your HTML:
<a onclick="doNewTab(1)" href="#">Tab1</a><br />
<a onclick="doNewTab(2)" href="#">Tab2</a><br />
<a onclick="doNewTab(3)" href="#">Tab3</a><br />

var tabId = 0
function buttonClick(obj) {
tabId = obj.id
}
<button onclick="buttonClick(this)">Button</button>

Related

hide back menu button if page was opened as a blank

How to hide a back button (in nav menu) if current page was opened with target="_blank".
in usual case this page is called as:
<a href="/about_us/" class="nav-li" >About Us</a>
in another case it is called with:
<a href="/about_us/" class="nav-li" target="_blank" >About Us</a>
The code at the target page for the back button is:
<label class="nav-li" for="back">Back</label>
<input class='Back' id = "back" type=button value="Back" onClick="history.go(-1)">
How to hide this button if opened as blank ???
Whole project is on Django
Just hide the button if the history object has a length of null less than 2 . This could be done with a css-class, pure css or direct with JS
[EDIT]:
I would add this to the onload event of the new form.
function init(){
if(history.length < 2){
document.getElementById('Back').style.display = none;
}
}
[...]
<body onload="init()">
[...]
You should heck the history object if the length is less or equal to 1 so it haven't a history, so you can hide your btn
window.onload = function (){
var hasHistory = history.length <= 1; //if has an history;
document.getElementById('cacca').style.display = hasHistory ? "none" : "block";
}

Use Cookies to prevent user clicking link twice

I am trying to prevent the class .activeAdv being added if the link within has it's URL stored in cookie, this cooke is added if user clicks links so basically I am trying to stop returning users clicking same link twice.
The link is by default hidden underneath a div which animates on addition of .activeAdv class, revealing link.
Current code is below along with codepen example of project. I'm guessing I need to wrap the activeAdv addClass in an IF conditional which:
Gets value of child link's href
Check to see if a matching cookie exists
Only add .activeAdv if condition returns false
I think I have the right idea and have got as far as setting cookie on click of link, I am struggling with the IF statement though, could anyone lend a hand?
http://codepen.io/Jambob/pen/wKyoRr
<article>
<div id="on-1" class="box">
<h2>1 dec</h2>
</div>
<div class="present">
content
www.google.com
</div>
</article>
// Checks for content within .present, if TRUE adds .activeAdv animation class
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).parent().addClass('activeAdv');
// When link clicked, store its URL in cookie
$( ".present a" ).click(function() {
$.cookie($(this).attr('href'), true);
});
if ( '(".present").html().trim().length > 0;' ) {
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}
After a bit of thinking I have come up with a different IF statement which may be along the right lines
// Checks if content exists
if ( '(".present").html().trim().length > 0;' ) {
// Checks if HREF of child link matches existing cookie (using a string for testing)
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}
So if :visited CSS pseudoclass isn't sufficient (it matches visited links), you can make use of localStorage, which is much more dedicated to this purpose. I created script which can be run out the Firebug console and colors non-visited links:
(function(links) {
// Load visited links from local storage
var visited = JSON.parse(localStorage["visited"]||"[]");
// Safety check
if(!visited instanceof Array) {
visited = [];
localStorage["visited"] = [];
}
function setClassToLinks() {
links.each(function(){
// Remember state - asume not visited
var linkVisited = false;
// Check for inner HTML
if(this.innerHTML.trim().length > 0) {
// Check if in list of visited links
if(visited.indexOf(this.href)==-1)
linkVisited = true;
else
console.log("Already visited: "+this.href);
}
else
// Skip empty links
return console.log("No inner HTML.");
// Reset color
this.style.color = !linkVisited?"":"red";
// And remove class
if(linkVisited)
$(this).removeClass("activeAdv");
else
$(this).addClass("activeAdv");
})
}
setClassToLinks();
// When link clicked, store its URL in LocalStorage
links.click(function() {
// Prevent duplicities
if(visited.indexOf(this.href)==-1) {
visited.push(this.href);
localStorage["visited"] = JSON.stringify(visited);
}
});
// [OPTIONAL] Update links realtime - triggers when local storage changes
window.addEventListener('storage', function (event) {
if(event.key=="visited") {
visited = JSON.parse(localStorage["visited"]||"[]");
// Change CSS
setClassToLinks();
}
});
})($("a"));
Neat aspect of my solution is, that the links automatically update when you browse in different tab (provided this tab has run the script).
The visited array may quickly grow, which is why I think cookie is such a bad idea.

Popup form on hover - how to make it the only one on the page?

I have 5 buttons 'Free call' on my site. On hover on them pops up contact form. I have a number of problems with it:
How to make the form be the only one on the page? I mean, from different buttons must be shown the same form. (For ex. I filled in the form in one place and when I hover other button, I see message 'You're done' or smth like that)
How to make the showing function work only once for every button? (The code below)
I tried to solve this problems but my methods didn't work
HTML
I have 5 such buttons on the page in different places
function showForm() {
var currentButton = $(this);
if ( currentButton.find('.popover-form') !== undefined ) {
var freeCallForm = "<form class=\"popover-form free-call-form\"><label for=\"\">Name</label><input type=\"text\"> <label for=\"\">Phonenum</label><input type=\"text\" value=\"+375\"><button>Call me!</button> </form>";
currentButton.append(freeCallForm);
}
}
$('.main-btn').on('mouseover', showForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="main-btn free-call">
<p>Use free call
<br/>
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
This function above unfortunately doesn't work. With if I tried to make function work only when .main-btn hasn't .popover-form.
And other problem is that on hover on different buttons anyway appends NEW form for every button. I can't find correct solution for this problem.
var isOpen = false;
function showForm() {
var currentButton = $(this);
if ( currentButton.find('.popover-form') !== undefined && !isOpen) {
var freeCallForm = "<form class=\"popover-form free-call-form\"><label for=\"\">Name</label><input type=\"text\"> <label for=\"\">Phonenum</label><input type=\"text\" value=\"+375\"><button>Call me!</button> </form>";
isOpen = true;
currentButton.append(freeCallForm);
}
}
$('.main-btn').on('mouseover', showForm);
//on modal close set isOpen back to false
The solution is the append() method. It moves DOM elements, not copies them (I thought so).
So I inserted my <form id="free-call-form"> to the end of the document, before </body>.
JS
function showForm() {
var currentButton = $(this);
if ( ( currentButton.find('.popover-form') !== undefined && !currentButton.existsFreeCall ) ) {
var freeCallForm = $('#free-call-form');
currentButton.append(freeCallForm);
currentButton.existsFreeCall = true;
}
}
$('.main-btn').on('mouseover', showForm);
In this code the same form moves from one to another button without copying and multiple appending.

Timer to reset Closing button once clicked back to it's "Before" state after 2 seconds

Hey there i've been having some difficulties with trying to figure out how to reset a button back to its previous state once its been clicked on. I know it involves a javascript timing, Can anyone help ive been trying all morning now.
function clickMute()
{ if (document.Mute.src=='http://www.showandtell.com/TRUMusicControl/images/BeforeClickMute.png'){
document.Mute.src='http://www.showandtell.com/TRUMusicControl/images/AfterClickMute.png';
}
else if (document.Mute.src=='http://www.showandtell.com/TRUMusicControl/images/AfterClickMute.png'){
document.Mute.src='http://www.showandtell.com/TRUMusicControl/images/BeforeClickMute.png';
}
}
<div id= "Mute">
<a href="#">
<img id="Mutebutton" name="Mute" onclick="clickMute()" src="images/BeforeClickMute.png" width="140" height="126" />
</a>
Firstly, remove the a (anchor) tag surrounding the image (mute button). Then just use the following code (to replace your function):
function clickMute(){
var strPath = "http://www.showandtell.com/TRUMusicControl/images/",
arrSrc = ["BeforeClickMute.png","AfterClickMute.png"],
button = document.getElementById("Mutebutton"),
index = (/Before/i.test(button.src)) ? 1 : 0;
button.src = strPath + arrSrc[index];
/* If you need the button to reset itself after a certain time... */
if (index) setTimeout(clickMute,2000);
}

jQuery 2nd click to call function

I have the following HTML
<a onclick="hi('#i_15', 'second_img.jpg'); return false;" href="http://google.com">
<img id="i_15" src="first_img.jpg" />
</a>
So, I don't want it to follow to google.com when it's clicked, but instead just call the hi function:
function hi(id, file){
$(id).attr("src", file);
}
This is supposed to enlarge the image (by swapping first_img.jpg to second_img.jpg.)
What can I do if I want to swap it back again? As in, click on the swapped image (second_img.jpg) and have it changed back to first_img.jpg; a reversal of what the hi function does.
As for not navigating to google.com when clicked, you can just change the href to be: href="#".
For the image swap, why not make your hi function work both ways, as a toggle? You could do this:
<a onclick="swapImage('#i_15', 'first_img.jpg', 'second_img.jpg');" href="#" >
<img id="i_15" src="first_img.jpg" />
</a>
function swapImage(id, firstImage, secondImage) {
var imageToLoad = $(id).attr("src") == firstImage ? secondImage : firstImage;
$(id).attr("src", imageToLoad);
}
Something like this in your hi() function should work.
function hi(id, file){
var $id = $(id);
if($id.attr("src") == file)
{
$id.attr("src", $.data($id, "orig"));
}
else
{
$.data($id, "orig", $id.attr("src"));
$id.attr("src", file);
}
}

Categories

Resources