IcedQuick
IcedQuick

Reputation: 61

Jquery if/else statement not working

I am having an issue with an if/else statement in wordpress. Note that the below Jquery code contains the mark-up to allow jquery to work in wordpress as per this article http://matthewruddy.com/using-jquery-with-wordpress/.

So the below function should work as follows:

-I check the document referrer to see if it contains the parameter blog

-If it does contain the word blog, I initiate a click on a isotope filter

-If it does not contain the word blog, I initiate two clicks on another isotope filter

jQuery(document).ready(function($) {
    $(window).load(function() {
        var lastUrl = document.referrer;
        console.log(lastUrl);
        if(lastUrl.search("blog")) {
            console.log('blog');
            $(".esg-filterbutton[data-filter='filter-blog']").click(); 
            return false;
        } else {
            $(".esg-filterbutton[data-filter='filter-social-media']").click()
            console.log('not-blog');
            $(".eg-post-id-1347").click(); 
            return false;
        }
    });
});

I added the console logs to check which part of the function is failing.

In other words, anyone going to this page directly should get the filter-social-media clicked automatically. If you go into a blog post through the filter and then click back or go back, it should initiate the blog filter again based on the referrer of the blog post.

Problem is that even if the URL does NOT contain the word 'blog' in it, I still get the console log and resultant action from the if statement and not the else statement. Any ideas what I am overlooking?

You can see it live here www (dot) dev (dot) stretchexp (dot) com/blog/ (apologies for writing the test URL like this, I dont want it indexed here).

Upvotes: 0

Views: 123

Answers (3)

Khaleel
Khaleel

Reputation: 1371

jQuery search returns position of first occurence.Just check it is greater or equal to zero.

if(lastUrl.search("blog") >=0 ) {}

Upvotes: 1

Arun Eapachen
Arun Eapachen

Reputation: 119

The value returned by lastUrl.search() would be the index of the matching word's first letter. So here in this case if 'lastUrl' does'nt have the word you are looking then it returns -1.

If condition will always be true for -1. That is the reason the else condition is not executed in your case.

if(lastUrl.search("blog") > -1){//your code}

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15403

Use .indexOf() in javascript

if(lastUrl.indexOf("blog") > -1) {

}

Upvotes: 1

Related Questions