Open page based on $(this) selector - javascript

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.

To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.

You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}

1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>

jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.

instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)

Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/

<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

Related

window is not loading immediately after clicking a link

When I click an anchor link, the current page should be loaded again immediately:
<a href="javascript:void(0);" class="BackToFirst"
onclick="popNav('BackToFirst');">Back</a>
function popNav(type) {
if(type == "BackToFirst") {
$(".first").show();
$(".second").hide();
$('.BackToFirst').click(function() {
document.location.href = window.location.href;
});
}
}
I expect that when a user clicks on the link, the current page will load immediately but it is taking some time to load.
It is unclear what you are trying to do.
show/hide is immediately undone when you reload the page
it is recommended to use location.reload(1) instead of setting the supposedly read-only document.location
you might want to use e.preventDefault instead of the javascript void
Are you absolutely sure this is not an X/Y problem? Can you explain the actual usecase?
var current = sessionStorage.getItem("which"); // does not run in a snippet
current = current ? current.split("|") : []
if (current.length) {
$("." + current[0]).show();
$("." + current[1]).hide();
}
$(".BackToFirst").on("click", function(e) {
e.preventDefault();
$(".first").show();
$(".second").hide();
sessionStorage.setItem("which", "first|second")
setTimeout(function() {
location.reload(1); // are you absolutely sure this is not an X/Y problem?
}, 500); //let the show/hide sink in
});
Back
Your Click handler is only assigning a new click handler to the link, try this which just directly navigates:
function popNav(type){
if(type=="BackToFirst")
{
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
}
}
I think that you got two concepts mixed up, the above code attaches a DOM event to the link directly on it, the other way would be to use JQuery to attach an event to that button like so:
HTML:
Back
Script:
$('.BackToFirst').click(function(){
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
});
If you still want to check the type then data attributes are a nice way to go when working with JQuery:
Back
$('.BackToFirst').click(function(){
if($(this).data('linktype') == 'BackToFirst'){
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
}
});
I think you are overcomplicating your code. You are binding onClick after you click on the element. I think something like this should be better.
HTML:
Back
JS:
function onClickHandler(type){
if(type !== 'BackToFirst') {
return;
}
$(".first").show();
$(".second").hide();
location.reload();
}

How to use JavaScript search on the same page while the user is still typing?

I'm trying to make a JavaScript search for a div within the same page. I'm currently using this code to display my search query:
$('.form-search').on('submit',function(){return false;});
$('.form-search .btn').on('click', function(e){
var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase();
$('div.staff-container .bold').each(function(){
var $this = $(this);
if($this.text().toLowerCase().indexOf(query) === -1)
$this.closest('div.staff-container').fadeOut();
else $this.closest('div.staff-container').fadeIn();
});
});
Here's a demo of an example with HTML and CSS:
DEMO
So I want to display the div, while the user is still typing. I know there is a refresh function, but I just cannot understand JavaScript. I'm a newbie student.
With a bit of refactoring you can both handle the click on the Search button and updating the search results as you type on the text input. This should work:
function updateResults() {
var query = $.trim($('.search-query').val()).toLowerCase();
$('div.staff-container .bold').each(function(){
var $this = $(this);
if($this.text().toLowerCase().indexOf(query) === -1)
$this.closest('div.staff-container').fadeOut();
else $this.closest('div.staff-container').fadeIn();
});
}
$('.form-search').on('submit',function(){return false;});
$('.form-search .btn').on('click', updateResults);
$('.search-query').on('input', updateResults);
Updated Jsfiddle: http://jsfiddle.net/1w8L0oeq/
Is that you want ?
You just have to listen 'input' event instead of click.
$('.form-search .search-query').on('input', function(e){ ... });
http://jsfiddle.net/817tfr03/
You can use the keyup() function on the searchfield as a trigger, instead of click().
Similar to what is done here

If Statements with data attribute - load two different templates based on what product has been clicked

I would like to open two templates based on the data attribute, if brand is SIM then open template1, if Samsung open the other.
Here is my code:
$('.item .show-detail').click(function(){
if($(this).find('[data-brand="SIM"]')) {
var myLink1 = $(this);
alert('hey');
$('.content .row').fadeOut({complete: function(){detailTemplate1('Voice',$(myLink1).parent().data('brand'), $(myLink1).parent().data('model'), $(myLink1).parent().data('subcat')); $('.content .row').fadeIn(400)}});
}else
($(this).find('[data-brand="Samsung"]'))
var myLink = $(this);
alert('link All');
$('.content .row').fadeOut({complete: function(){detailTemplate('Voice',$(myLink).parent().data('brand'), $(myLink).parent().data('model'), $(myLink).parent().data('subcat')); $('.content .row').fadeIn(400)}});
})
You have a lot of problems in your code.
You can't specify a condition for else, you have to say else if
Wrap else if block in figure brackets.
Use length to find if element exists.
This is assuming that data-brands exist inside item element you're clicking on:
$(document).ready(function(){
$('.item').click(function(){
if( $(this).find('[data-brand="SIM"]').length ) {
var myLink1 = $(this);
alert('SIM');
}
else if ( $(this).find('[data-brand="Samsung"]').length ) {
var myLink = $(this);
alert('Samsung');
}
});
});
http://jsfiddle.net/f32epg16/
jquery objects will always be truthy, you need to check the length.
if($(this).find('[data-brand="SIM"]').length)
Second else does not have a clause. You need to either drop it or use else if.
Try this
$(document).ready(function(){
$('.item .show-detail').click(function(){
if($(this).attr("data-brand")=="SIM")
alert("SIM");
else if($(this).attr("data-brand")=="Samsung")
alert("Samsung");
});
});
Use jquery attr method to find its value and do the relevant work

jQuery check if target is link

I have a global function to capture clicks.
$(document).click(function(e){
//do something
if(clickedOnLink)
//do something
});
I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.
http://jsfiddle.net/Af37v/
You can try to see if the element you clicked on either is or is a child of an <a> tag.
$(document).click(function(e){
if($(e.target).closest('a').length){
alert('You clicked a link');
}
else{
alert('You did not click a link');
}
});
I believe using is will actually have better performance than the answers suggesting closest:
$(e.target).is('a, a *');
This checks if the element itself is an a or if it is contained with an a.
This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
If the exact target is link, then you can use .is()
Example:
$(".element").on("click", function(e){
if($(e.target).is("a")){
//do your stuff
}
});
EDIT:
If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length
Example:
$(".element").on("click", function(e){
if($(e.target).closest("a").length){
//do your stuff
}
});
With jquery just get the tagName attribute
$("a").prop("tagName");
Updated:
You could check if the target is an a or if a parent is an a.
$(function () {
$(document).on('click', function (e) {
$target = $(e.target);
if ($target.closest('a').length > 0) {
alert('i am an a');
}
});
});
http://jsfiddle.net/8jeGV/4/
You can test if there's a <div> under <a> by testing if the .children() <div> has anything inside it. If nothing is inside, or there is no <div>, the if statement will return false.
I suggest this code:
$(document).click(function(e){
var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false),
//run code
if ( willRedirect === false ){
e.preventDefault();
//the link will not redirect
if ( $(this).children('div').html() ){
//there is a <div> inside <a> containing something
}
else {
//there is no <div> inside <a>
}
}
else {
//the link is not pointing to your site
}
});

jQuery ~ Adjusting href before following it

I have a link with a series of checkboxes, due to the legacy code, when the user clicks on a checkbox the value of it is appended as a comma deliminated list to the href.
The trouble is that now that I'm updating the code, I'm finding that the href is being followed quicker than the href is being adjusted, thus the list is being excluded.
I have tried using preventDefault() which is great, but I have no idea how to continue the default action after changing the href to include the selected values.
I should also mention that it is not viable to change it to a regular form, as there is an additional option set in a lightbox after submission. (Don't ask me why, it's lunacy in my book)
So far I've got to
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
e.preventDefault();
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
$(this).attr('href',href);
// Continue to follow the link
// Faking a user click here with $(this).click(); obviously throws a loop!
});
});
});
Just set the location to the adjusted href value and return false from the handler to avoid taking the original link.
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
location.href = href;
return false;
});
});
});

Categories

Resources