It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've been asked by a friend to set up a web page whose background changes only once when any of the links are clicked. I've tried a few examples given on this site and looked at a few on Google, but they are pretty much all gallery-style cyclical changes. Perhaps I'm just frustrated and not seeing the trees for the forest...
The page is # mysite/julie
The images are # mysite/julie/images/blogbka.png and /images/blogbk.png
I used the solution found below ( https://stackoverflow.com/a/11362465/1506620 )
Thank you all for your help.
var is=true;
document.body.onclick = function( e ) {
if ( e.target.tagName === 'A' ) {
if(is){
document.body.style.background='url(http://adultdave.co.uk/julie/images/blogbka.png)';is=false;}
}
};
I hope this is what you want, i.e change image only once. If not, do tell me.
var ischange=true;
document.onclick=function(e){
if( e.target.tagName === 'A' &&ischange)
{
document.body.style.background='url(/*Image url*/)';
ischange=false;
}
}
DEMO
Here on each page load a variable ischange is initialized true, and when any link is clicked, the background is changed and ischange is set to false, so that no more background changes are allowed.
One approach would be to use a function that wraps another function, only performing the inner function the first time its called. This is a fairly generic version of such:
var once = function(fn, thisObj) {
var called = false;
var val;
return function() {
if (called) {return val;}
called = true;
val = fn.apply(thisObj || null, arguments);
return val;
};
};
Then you can wrap your MooTools event listener inside a call to once() and know that it will only be called one time. This can be a rather elegant solution to such problems.
I have done bins for changing page background randomly on click of each link using jQuery.
So, please follow the steps:
1) Include Latest Jquery java script file on header.
2) HTML:
<div>
<p>
When you click on following paragraph link, every time it will be changed random background of the page
</p>
<p>
You have a present that was really memorable. It could have been given for an
<a href="#">
important occasion
</a>
or just for no reason at all. Tell us about the present and why it was memorable. Include the reason it was given, a
<a href="#">
description
</a>
of it, and how you felt when you got it.
The objective is to write a
<a href="#">
narrative essay
</a>
about this present you were given
The subject is a
<a href="#">
memorable present
</a>
The three main subtopics are:
<ul>
<li>
<a href="#">
the reason it was given
</a>
</li>
<li>
<a href="#">
a description of it and
</a>
</li>
<li>
<a href="#">
how you felt when you got it
</a>
</li>
</ul>
</p>
</div>
CSS:
body{
background:url("http://www.freeppt.net/background/modern-pink-floral-backgrounds-for-powerpoint.jpg");
}
JQuery:
var items = new Array();
items[0] = "http://www.publicdomainpictures.net/pictures/10000/nahled/abstract-orange-background-29541280675430Trj9.jpg";
items[1] = "http://www.psdgraphics.com/wp-content/uploads/2011/03/red-flowing-background.jpg";
items[2] = "http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg";
items[3] = "http://www.purplebackgrounds.net/wp-content/uploads/2011/10/purple-heart-background-680x544.jpg";
items[4] = "http://www.freeppt.net/background/beautiful-on-green-backgrounds-for-powerpoint.jpg";
$(function() {
var bg_img = '',
last_bg = '';
$("a").click(function() {
bg_img = items[Math.floor(Math.random() * items.length)];
if (last_bg == bg_img) bg_img = items[Math.floor(Math.random() * items.length)];
last_bg = bg_img;
$("body").css('backgroundImage', 'url(' + bg_img + ')');
});
});
Try DEMO on http://codebins.com/codes/home/4ldqpbc
As I see it, you'll want to provide the user's browser a cookie to chew on and track the click event(s) for all anchor tags on the page. You could do something like:
Mock Html
<ul id="ActionLinks">
<li>Click Me!</li>
<li>Clear Cookie!</li>
</ul>
jQuery Code
<script type="text/javascript">
$(document).ready(function () {
// Array to store options
var settings = {
getRadomImage: function () {
//Update this with your different images.
var items = [
"http://adultdave.co.uk/julie/images/blogbka.png",
"http://adultdave.co.uk/julie/images/blogbka.png",
"http://adultdave.co.uk/julie/images/blogbka.png",
];
var img = items[Math.floor(Math.random() * items.length)];
return img;
},
cookieName: "tracker",
cookieOpts: { expires: 1} //cookie plug-in options
}
//Capture all tracked clicks
$(".tracked-click").click(function (e) {
//Check to see if there is a cookie for the user.
if ($.cookie(settings.cookieName) != "true") {
var img = document.createElement('img');
img.src = settings.getRadomImage();
//Load up the new image and show it once it's loaded.
img.onload = function () {
//Fade out the body and fade back
/*
$("body").fadeOut(function() {
$(this).css({ 'background-image': 'url(' + img.src + ')' }).fadeIn(4000);
});
*/
$("body").css({ 'background-image': 'url(' + img.src + ')' });
};
//Set the cookie for the client for tracking.
$.cookie(settings.cookieName, true);
}
});
//Action for clearing cookie.
$(".action-clear-cookie").click(function () {
$.cookie(settings.cookieName, null)
});
});
</script>
Code References
https://github.com/carhartl/jquery-cookie
Set up a jQuery script :
$("a").click(function(evt) {
$('body').css("background-image", "url(/myimage.jpg)");
}
If you want it to change between the pages, use a session cookie (i used "simpler" functions, see (this)[http://jquery-howto.blogspot.fr/2010/09/jquery-cookies-getsetdelete-plugin.html] for instance) :
if (getCookie('isAlreadyVisited') == 1) {
$('body').css("background-image", "url(/myimage.jpg)");
}
setCookie('isAlreadyVisited', 1);
You can also handle this by setting the cookie on the server side and add a class to your body, which changes the background (you won't have Flash of Unstyles Content this way).
body {
background-image: url(img1.jpg);
}
body.visited {
background-image: url(img2.jpg);
}
Related
following problem:
I am using ng-repeat to generate a list of items. If the user clicks on a special marker on my webpage above, the following function receives an event an scrolls down to the corresponding item. In addition to scrolling down I would like to highlight the item until the user moves the mouse again. My problem ist that do to this I need to manipulate the css class of one single element of my ng-repeat list. I thought it might be possible because every ng-repeat element gets its own local scope...but I don't find the solution.
Part of my directive:
//if a marker is clicked, the following code should bring the user to the corresponding item
$rootScope.$on("Scroll_to_product", function (event, args) {
product.gotoElement(args);
});
/*function which takes the class id of an html element as argument and brings
the user to the corresponding product*/
product.gotoElement = function (args) {
var elementID = 'product-' + args;
$location.hash(elementID);
// call $anchorScroll()
$anchorScroll();
}
Any help would be great,
Thanks, Hucho
I think this woking Plunker example may help you
Plunker link
$scope.idSelectedVote = null;
$scope.setSelected = function(idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
console.log(idSelectedVote);
}
.selected {
background-color: red;
}
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected : vote.id === idSelectedVote}">
</ul>
it almost broke my head, but finally was easy:
product.highlightFeature = function (args) {
var id = '#'+ 'feature-' + args;
var myEl = angular.element( document.querySelector( id ) );
myEl.addClass('feature-highlight');
};
It is easy and fast..; yet thanks for your help.
This might help others...
Best
Hucho
I'm attempting to make a menu bar that can have <li> elements added and removed. So far so good, but when I try and remove them I'm running into issues. I've toyed with this for a couple hours and now I'm wondering if this whole process could just be made easier (maybe an object?).
Anyways, here's the full code (80 lines), with comments to follow along.
var tabs = $('.accountSelectNav');
var titles = [];
var listItems = [];
// when the page loads check if tabs need to be added to the ul (menu bar)
$(document).ready(function(e) {
if ($.cookie('listItems') != null) {
console.log('not null');
//return "listItems" to it's array form.
listItems = JSON.parse($.cookie('listItems'));
$('.accountSelectNav').append(listItems);
}
});
$('.selectTable td:first-child').on('click', function(e) {
$('#home_select').removeClass('navHighlight');
//grab the text value of this cell
title = $(this).text();
$.ajax({
url:'core/functions/getAccountId.php',
type: 'post',
data: {'title' : title}
}).fail (function() {
alert('error');
}).done(function(data) {
accountId = $.trim(data);
// store values in the cookie
$.cookie('account_id', accountId, {expires : 7});
$.cookie('title', title, {expires : 7});
window.location = ('home_table.php');
});
// make sure the value is NOT currently in the array. Then add it
var found = jQuery.inArray(title, titles);
if (found == -1) {
titles.push(title);
addTab();
}
// make sure the value is NOT currently in the array. Then add it
found = jQuery.inArray(title, listItems);
if (found == -1) {
addListItem();
//place <li>'s in cookie so they may be used on multiple pages
$.cookie('listItems', JSON.stringify(listItems));
};
});
$("body").on("click", ".deleteImage", function (e) {
var removeTitle = $(this).closest('li').find('a').text();
var removeItem = $(this).closest('li')[0].outerHTML;
//remove title from "titles" array
titles = jQuery.grep(titles, function (value) {
return value != removeTitle;
});
//remove <li> from "listItems" array
listItems = jQuery.grep(listItems, function (value) {
return value != removeItem;
});
// this shows the <li> is still in the listItemsarray
console.log(listItems);
// put the array back in the cookie
$.cookie('listItems', JSON.stringify(listItems));
removeTab(this);
});
$("body").on("mouseover", ".accountSelectNav li", function(e) {
$(this).find('.deleteImage').show();
});
$("body").on("mouseleave", ".accountSelectNav li", function(e) {
$(this).find('.deleteImage').hide();
});
function addTab() {
tabs.append('<li class="navHighlight">' + '' + title + '' + '' + '<img src="images/delete.png" class="deleteImage"/>' + '' + '</li>');
};
function removeTab(del) {
$(del).closest('li').remove();
}
function addListItem() {
var s = ('<li class="navHighlight">' + '' + title + '' + '' + '<img src="images/delete.png" class="deleteImage"/>' + '' + '</li>');
listItems.push(s);
}
So you see I have two arrays of equal length that should always be the same length. One stores the title to be displayed in the tab, the other holds the html for the <li> which will be appended to the <ul>. I have no problem removing the title from its array. However removing the <li> from it's array is becoming a rather big hassle. You see when I get the <li> element after its been inflated the html inside does not exactly match what was put in, the browser adds style elements.
Example, the variable "removeItem" represents the html value of the selected <li> I wish to remove. It looks like this:
<li class="navHighlight">Test1<img src="images/delete.png" class="deleteImage" style="display: inline;"></li>
yet the value in my array "listItems" looks like this:
<li class="navHighlight">Test1<img src="images/delete.png" class="deleteImage"/></li>
So my attempt at removing it from my array always fails because they aren't a perfect match.
Now my question is how do I remove this <li> item? Also is there an easier way to do this whole process and I'm just not seeing it?
Thanks for your time.
EDIT
Fiddle by request here
Easiest way I can explain it.
Click the link to the fiddle.
Click any cell in the "App Name" column
This will add a <li> to the <ul> (menu) above of the table
When you hover over the <li> a picture appears
Click the picture
This should remove the <li>, both from the <ul> and from the array listItems
right now it does not
In the process of making this easier to check, I've taken your JSFiddle and did the following:
removed extra console.log and comments
removed interaction with cookies (since I did not have them in the first place, I figured they wouldn't just the first scenario)
After doing so I reached a point (you can see it here) where the desired functionality just works.
I even went ahead and removed the ajax stuff because that alert was driving me crazy. (here)
Since this works fine, my guess is that your issue lies between the lines that I removed.
Your usage of cookies is as follows:
To load existing tabs and add them back again
To save account_id and title, which is not used back again
To persist the listItems after a new item has been added
I then opened up the console with your version of the fiddle and the execution of javascript stops at $.cookie() with the error undefined is not a function.
This clearly indicates that the issue present in the Fiddle is that jQuery.cookie is not present and so those calls are halting the execution of the rest of your script. This also explains why it just started working when I took them out.
I posted the whole process of how I got there to indicate how I trimmed down the problem to specific parts, which is useful to reduce the problem space. When you're out of options and reach a place when you're lost, it's easier to post a question with less code and the specific part of the problem that you've identified. This will help you in finding the issues that you're facing and StackOverflow to provide proper answers to your questions.
Hope it helps!
Here is the solution I came up with. It should be much easier for people to understand than my original post. Although it's a long read it may be worth it, especially for new developers.
The point of this code is to make a menu bar out of an un-ordered list or <ul>. The menu bar needs to be used on multiple pages. So I'll be using cookies.
I start with this code to get a text value from my table.:
$('.selectTable td:first-child').on('click', function(e) {
// This value will be used later for the name of the tab or `<li>` inside our menu bar or `<ul>`
title = $(this).text();
});
Then I place the value in an array. I do this only if the array does not already have this string inside it. I do not want duplicates:
var found = jQuery.inArray(title, titles);
var titles = [];
if (found == -1) {
titles.push(title);
}
Then I store the array into a cookie, using a library like this:
$.cookie('titles', JSON.stringify(titles));
Now when any page loads that needs this menu bar I run this code to check if there are any values:
$(document).ready(function() {
if ($.cookie('titles') != null) {
titles = JSON.parse($.cookie('titles'));
}
});
Now I need to loop through the array. When I loop through the array I have to do 3 things:
1) Grab the string value.
2) Add the html to my new string so it becomes a list item or <li>.
3) Append the newly created <li> to our <ul>.
Like so:
for(var i = 0; i < titles.length; i++) {
var str = titles[i];
var listItem = '<li class="navHighlight">'
+ '<a href="#">'
+ str
+ '</a>'
+ '<a href="#">'
+ '<img src="images/delete.png" class="deleteImage"/>'
+ '</a>'
+ '</li>';
$('.accountSelectNav').append(listItem);
}
Now, if I want to remove this <li> I click the delete image found inside our <li>. What delete image you say? Look at the html I added again. You will see I add an <img> tag in there.
Now delete like so:
$("body").on("click", ".deleteImage", function (e) {
// grabs the text value of my li, which I want to remove
var removeTitle = $(this).closest('li').find('a').text();
// runs through my titles array and returns an array without the value above
titles = jQuery.grep(titles, function (value) {
return value != removeTitle;
});
});
Then I simply place the new array inside my cookie once again. Like this:
$.cookie('titles', JSON.stringify(titles));
And finally I remove the tab like this:
removeTab(this);
function removeTab(del) {
$(del).closest('li').remove();
}
Yay, I'm done. So now, if anyone has a more elegant way of accomplishing this I'm listening. I have no doubt there's a better way, javascript/jQuery isn't even close to my strong point.
The full code can be found here.
I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
I have received help earlier in another question about some jQuery transitioning and I got my website to behave properly, but now I need to get a bit deeper into this jQuery transitioning...
I need a particular effect/transition to happen based on the hashtag that is written in the address bar. This is the code provided by the other question by pckill:
$('.nav').on('click', 'li', function(){
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
});
And this is the HTML: http://pastebin.com/pu7jmefC
Let's say, for example, I link someone to http://mywebsite.com/index.php#remote, I want the user to be transitioned with jQuery to the proper div. The approach above works perfectly with the menu I have, but I want to be able to share the URL with someone and they'd still be able to get directly to the proper div.
I think the code above needs some altering to make it do what I seek, but I unfortunately, I'm not that good in Javascript/jQuery.
I guess we'd have to touch the code somewhere around here: $('#inner > div').not(current).
I know we have window.location.hash to work with hashtags, but I have no idea how to put it to use in the code above.
Ideas?
If you just need to check the hash on page load and perform an action accordingly, that's really simple. First of all you need to move the logic of transitioning to a div into a separate function, say transitionToDiv:
function transitionToDiv(id) {
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
}
And change the click event (the code in your question) to:
$('.nav').on('click', 'li', function() {
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
transitionToDiv(id);
}
Now, to transition to a div on page load based on the address hash, simply add these lines at some point after page load:
var id = window.location.hash.substr(1);
transitionToDiv(id);
The easiest way to see the problem is checking the code here: http://www.studioimbrue.com/beta
What I need to do is once a thumbnail is clicked, to removed the "selected" class from all other thumbnails that are in this same or without removing them from the other galleries on the page. Right now, I have everything working except the class removal. Someone helped me in another question but wasn't quite specific enough (my javascript skills aren't all that great!) I'm using jQuery. Thanks for the help.
Well in that case, I'm not sure why this doesn't work properly:
$(document).ready(function(){
var activeOpacity = 1.0,
inactiveOpacity = 0.6,
fadeTime = 100,
clickedClass = "selected",
thumbs = ".thumbscontainer ul li img";
$(thumbs).fadeTo(1, inactiveOpacity);
$(thumbs).hover(
function(){
$(this).fadeTo(fadeTime, activeOpacity);
},
function(){
// Only fade out if the user hasn't clicked the thumb
if(!$(this).hasClass(clickedClass)) {
$(this).fadeTo(fadeTime, inactiveOpacity);
}
});
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var previous = $(thumbs+'.'+clickedClass).eq();
var clicked = $(this);
if(clicked !== previous) {
previous.removeClass(clickedClass);
}
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
});
});
I see you're using jQuery (and have edited your question accordingly).
With jQuery, it's really easy to get a list of matching elements using CSS syntax:
var list = $('#parentId > .selected');
That gets a list of the direct children of the element with the ID "parentId" that have the class "selected". You can then do things with them, such as:
list.removeClass("selected");
Then add "selected" to the element you want to select.
Edit I think this should do it:
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var clicked, previous;
clicked = $(this);
if (!clicked.hasClass(clickedClass)) {
previous = $(thumbs+'.'+clickedClass);
previous.removeClass(clickedClass).fadeTo(fadeTime, inactiveOpacity);
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
}
});
I'm assuming there that the "selected" class isn't necessary for the fade effect to look right.
Note how the above will completely ignore the click if the clicked element already has the class. If you don't want that, remove the hasClass check and add .not(clicked) to the end of the previous = $(thumbs+'.'+clickedClass) line, but I don't know what your fade in would do at that point if you've already done it once.
I'm not getting the hover stuff; I thought you wanted this to happen on click, not hover.
You should take a look at
jQuery.removeClass()
So the point would be to first iterate trough all the images and unset the classname and than set the class on the active one.
Use .closest('.jcarousel-clip') to get the parent div,
then find all the thumbnails and use .removeClass('selected').
Hi Andy it isn't clear your question, but I am going to try to help you.
I am trying to help, and my skills on javascript arent that good either, plus I am not sure if I undertood the question right, please, dont vote me down.
function focusme(){
document.getElementById("focusme").focus();
}
function changeToCurrent(obj){
var menucont = document.getElementById('menu');
var arrLink = menucont.getElementsByTagName('a');
for (var i = 0 ; i < arrLink.length; i++){
arrLink[i].className='';
}
obj.className = "current";
}
<div class="menu" id="menu" >
<a href='' id='focusme' onclick='changeToCurrent(this)'>link1</a>
<a href='' onclick='changeToCurrent(this)'>Once Only link2</a>
<a href='' onclick='changeToCurrent(this)'>link3</a>
<a href='' onclick='changeToCurrent(this)'>link4</a>
<a href='' onclick='changeToCurrent(this)'>link5</
link6
</div>
Hope it helps.