I want to trigger a function when the user is on a section of the page with a specific ID (either through a link or scroll). This is what I have now but it's not working.
$(document).ready(function() {
if (window.location.pathname == '/index.html#contact') {
console.log('Viewing contact form');
}
});
UPDATE: Found what I was looking for. This is what I used:
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#contact').offset().top - 50) {
$('.modal').modal('hide');
}
});
The "- 50" is to account for my margins and paddings. When using the subtract symbol it 'assumes' your section starts higher on your page. For lower, use addition.
The "$('.modal').modal('hide');" is not needed. This is to hide a bootstrap modal when the user is on the #contact section of the page.
The window.location property in Javascript returns a location object. If you want to match a specific anchor link you need to use the hash property of the location object. Here's a list of all properties of location objects: http://www.w3schools.com/jsref/obj_location.asp.
You could check for window.location.pathname+window.location.hash
$(document).ready(function() {
if (window.location.pathname+window.location.hash == '/index.html#contact') {
console.log('Viewing contact form');
}
});
because window.location.pathname does not include the part after the hash.
Your Html code
<div id="contact">
</div>
Your Javascript code
$("#contact").scroll(function() {
/*do whatever you want*/
});
Related
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.
I want to check if following code is dynamically created or not :
<div id="js_contact_error_message" style="display: block;">
<div class="error_message"> <!-- For this div only I want to apply the above written inline css-->
Please enter full name
</div>
How should I check this in jQuery? If it's present execute the if condition.
Thanks.
The condition that <div class="error_message">...</div> is present within <div id="js_contact_error_message" style="display: block;">...</div> must get checked.
I tried below code but it didn't work for me:
if ($("#js_contact_error_message").find("div.error_message").length != 0) {
alert("Bestow");
}
You can do this:
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
Note:
You need to place this line of code where you have done your js validations.
or you may try with this:
$(document).on('DOMSubTreeModified propertychange',function(){
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
});
Try,
For using if-else condition.
if($("#js_contact_error_message").find(".error_message").length > 0)
{
alert("div present");
}
else
{
alert("div not present");
}
But as you stated in your question, you want to apply specific inline css. Make a class for the style what you have and you can use the ollowin code.
$("#js_contact_error_message").find(".error_message").addClass("your_style_class");
This code will apply your css class only for those divs which match the condition.
EDIT:
If you want to add your style to the div, you can try defining it in your page, which will apply as soon as the div is added dynamically.
<style>
#js_contact_error_message .error_message
{
/*your inline style*/
}
</style>
if($("#js_contact_error_message .error_message").length > 0)
{
alert("div is present");
}
else
{
alert("div is not present");
}
Demo
You can check it in many ways.. few of them are :
Use $("#js_contact_error_message").has('div') function of jquery to get the specific element Has in JQuery
If the error message div is the only div to be inside the main div then you can check it as :
Check the element $("#js_contact_error_message").html() is blank or use $("#js_contact_error_message").children() (Children in JQuery) to check if it has any childrens.
Hope this helps :)
make sure your html composition is correct , opening and closing. Then try this code.
if($("#js_contact_error_message").length > 0)
{
$("#js_contact_error_message").find(".error_message").addClass("style_class");
}
Hello fellow stackoverflow members who use bootstrap! I appreciate your time and input. I am having trouble implementing a jQuery.scrollintoview with bootstrap scrollspy.
http://jsfiddle.net/aKK2k/1/
Above is fiddle, scrollspy is broken but the scrollintoview should still work, or am i mistaken?
Nav buttons that move the page:
<li>
<a href="#section-2" id="a-section-2">
Products
</a>
</li>
Below is the scroll-to-section
<h3 class="center" id="section-2">
So, how can Day & Night help your business today?
</h3>
Below is the JS that handles the page scrolling / hiding url / etc.
The implementation happens at
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
The whole JS
<script>
$("document").ready(function() {
$(document).on('click','.navbar li a',function(event) {
event.preventDefault();
if($.trim($(this).html())!='FAQ'){
//if($.trim($(this).html())!='FAQ' || $.trim($(this).html())!='FAQ2'){
var offset = $('#myNavbar').height()+30;
if ($(window).width() <= 768) {
var offset = 100;
}
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
scrollBy(0, -offset);
}
else
{
window.location.href = $(this).attr('href');
}
});
//document.referrer returns the url from which this page has been entered,
//we will use this to check if we are redirected from FAQs page
var previous_url = document.referrer;
if(previous_url=='http://dnwebdev.com/dev/faq/'){
//if we were redirected from FAQ page, we would have a #section-value in our url
//hash here fetched that value
var hash = document.URL.substr(document.URL.indexOf('#')+1);
//this is the important part, we are gonna trigger that the
//#section-value passed in url is _clicked_. And so the browser will
//scroll down to that section
$('.navbar li a#a-'+hash).trigger('click');
//once it scrolls down, this deletes the #section-value from url
history.pushState('', document.title, window.location.pathname);
}
});
function close_toggle() {
$('.nav a').on('click', function () {
if ($(".navbar-toggle").css("display") != "none") {
$(".navbar-toggle").click();
} else {
$('.nav a').off('click');
}
});
}
close_toggle();
$(window).resize(close_toggle);
</script>
Currently the page jumps when an "easeOutExpo" is what we are going for.
I am very new to JS, any input is appreciated.
The website is http://dnwebdev.com/
I added jqueryUI, declared jquery before ui, but the scroll still won't work.
Robert
You are invoking scrollIntoView on the raw DOM element, when you want to invoke it on the jquery matched set. Remove the [0] and try this:
$($(this).attr('href')).scrollIntoView(250, "easeOutExpo");
fiddle: http://jsfiddle.net/aKK2k/7/
(i've also added the jquery stuff to your fiddle).
The code already creates a navigation based on a JSON-file. The url are accessible by writing data.chapter[].subchapter[].url, the according title through data.chapter[].subchapter[].title
In case you are interested in that part or want the complete code, I uploaded it there: http://fabitosh.bplaced.net/SkriptET_iFrame_v2/
The goal now is to create a right sidebar which shows the links to the next and previous files in the structure. My approach is below.
What confuses me, is that back() is called until subchap is zero, when a link in #left is being clicked on. It should only be called when the previous-link is being clicked on. What do I have to change in order to achieve that?
Thanks a lot already!
var chap; //position in the array of the currently open chapter
var subchap; //position in the array of the currently open subchapter
function update_right() {
var path = data.chapter[chap].subchapter;
//Previous Page
if(subchap > 0) {
$("#prev").html("<b>Previous:</b><a href='"+path[subchap-1].url+"'>"+path[subchap-1].title+"</a><br/>");
$("#prev > a").click(back());
} else { //subchap == 0
$("#prev").html("");
};
}
function back() {
subchap--;
update_right();
}
$(document).ready(function() // DOM needs to exist in order to be able to add stuff in there
{
...Navigation being built up...
//------ onClick Navigation
$('#left > ul > li > a').click(
function(e)
{
chap = $(this).attr("data-chap");
subchap = $(this).attr("data-subchap");
update_right();
}
);
});
I would like to be able to look in the first span within a div with a class of t_links and buy and detect if the string Account appears. If it does then I want to set some tracking code in jQuery/JavaScript.
There will always be one span within this div. How can I search the contents for an instance of Account using jQuery?
<div class="t_links buy">
<span><a class="" href="https://www.ayrshireminis.com/account/login/">Account</a></span>
</div>
:contains is what you're looking for:
$(".t_links.buy span:first:contains('Account')")
http://api.jquery.com/contains-selector/
Edit: Added first as #adeneo pointed out. This will ensure that it's the first span that you're looking at.
Try (See Demo)
$(document).ready(function () {
if($('.t_links.buy span').text().indexOf('Account')) {
// code
}
});
Or
$(document).ready(function () {
if($(".t_links.buy span:contains('Account')").length) {
// code
}
});
Span has exact match :
if ($("span:first", ".t_links.buy").filter(function() {
return $(this).text() === 'Account';
}).length) {
//set tracking code
}
Span contains :
if ($("span:first", ".t_links.buy").filter(function() {
return $(this).text().toLowerCase().indexOf('account') != -1;
}).length) {
//set tracking code
}
If there is only one span, you can drop the :first.