Changing content on a page using javascript via a url string -
i'm designer not js coder great on this.
using javascript or jquery how replace content on page via string in url?
so if content 'a' normal content via http://www.example.com , if 'a' replaced content 'b' via http://www.example.com/index.html?content=b.
example:
content a
<div id="video-player"> vimeo code </div> to replaced content b
<div id="video-player"> youtube code </div> via string in url http://www.example.com/index.html?player=youtube if there no string in url default , show vimeo code
edit
ok on html page now
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="js/test.js"></script> </head> <body> <div id="video-player"> vimeo </div> </body> </html> and in js page
window.location.href.split('?')[1].split('&')[0].split('content=')[1] var content_value = window.location.hash.substring(1) // hashses or var content_value = window.location.href.split('?')[1].split('&')[0].split('content=')[1] // ? if (content_value === "b") { $('#video-player').html(vimeo_code); } else { $('#video-player').html(youtube_code); is right?
the easiest wat use hash tag. use ? harder implement. instead of index.html?content=b use index.html#b , can reference using window.location.hash.substring(1) give b in scenario. can use if statement check value , adjust content accordingly.
alternatively, if need use ? can use window.location.href.split('?')[1].split('content=')[1] not guaranteed work in every situation, if have more 1 variable there. multiple variables use
window.location.href.split('?')[1].split('&')[0].split('content=')[1] your complete code this:
$(function () { var youtube_code, vimeo_code, content_value; youtube_code = "the code youtube goes here"; vimeo_code = "the code vimeo goes here"; content_value = (typeof window.location.href.split('player=')[1] !== "undefined") ? window.location.href.split('player=')[1] : ""; if (content_value === "youtube") { $('#video-player').html(youtube_code); } else { $('#video-player').html(vimeo_code); } }); you use else ifs if wanted more content options. use 1 of top 2 lines depending on option chose.
edit: changed code complete code (and optimised bit). not need add else apart changing youtube_code , vimeo_code correct values.
edit: optimised , made check if there player= in url.
Comments
Post a Comment