4

On my website id like to run a jQuery function if my url contains the word 'test'

All im trying to do is if my url contains the 'rest' string then add a margin to an element on the page?

Ive added a jSfiddle to try and show what Ive done so far.

$(document).ready(function(){         
    // How can I check to see if my url contains the word 'TEST' then run the below function?
    $('.block-widget').css('margin-top, 252px')     
});

6 Answers 6

9

Use window.location to get the current location url..

Based on the condition you can then apply the margin top property.

$(document).ready(function(){         
     var pathname = window.location.pathname;
     if(pathname.indexOf('text') > -1){
        $('.block-widget').css('margin-top, 252px');
     }     
});
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think that the path is the only part where test could/should appear
@Bergi we will assume the OP knows enough about programming to inspect window.location themselves & find the solution. :D
2
$(document).ready(function(){         
   if (document.url.match(/test/g)){
     $('.block-widget').css('margin-top, 252px')     
  }
});

Comments

0

Take a look at this link that contains details that you need to know about URL.

https://developer.mozilla.org/en-US/docs/DOM/window.location

$(document).ready(function(){         
    if (window.location.href.indexOf('rest') >= 0) {
      $('.block-widget').css('margin-top, 252px')     
    }
});

Comments

0

Get the path name:

var pathname = window.location.pathname;

Then check if it contains "TEST".

if (pathname.toLowerCase().indexOf("test") >= 0)

1 Comment

You're using toLowerCase() so you should check for 'test'
0

try this

$(document).ready(function(){         
    var patt=/test/g;
    if(patt.test(window.location.pathname)){
    $('.block-widget').css('margin-top, 252px')  
  }   

});

Comments

0

name*='keyword' selector is true option.

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>

Resource: https://api.jquery.com/attribute-contains-selector/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.