Lucas
Lucas

Reputation: 3715

Change position of the element

What I need to do is to move the div element around the text string depending on the pressed arrow key. Actually the HTML string would look following:

mytextpharse<div class="blink"></div>

then, on the .keyUp event I'm gonna pick informations on which button was pressed (event.which) and if pressed key is the 37 or 39 (which are: left, right arrow keys) I would like to move the div.blink to the right direction based on the event.whichbutton pressed. So if I would press the left arrow key twice it should format the string into the following format:

mytextphar<div class="blink"></div>se

Could that be done in jQuery? If so, I need ideas on which functions should I use.

Upvotes: 0

Views: 119

Answers (2)

Volkan Ulukut
Volkan Ulukut

Reputation: 4218

this should do the trick (using search and substr): (jsfiddle)

$( document ).keyup(function(e) {
  if(e.which == 37)
  {
      var str = $("#content").html();
      str = str.substr(0,str.search(/<div/)-1) + '<div class="blink"></div>' + str.substr(str.search(/<div/)-1,1) + str.substr(str.search(/<\/div>/)+6);
      $("#content").html(str)
  }
  if(e.which == 39)
  {
      var str = $("#content").html();
      str = str.substr(0,str.search(/<div/)) + str.substr(str.search(/<\/div>/)+6,1) + '<div class="blink"></div>'  + str.substr(str.search(/<\/div>/)+7);
      $("#content").html(str)
  }    
});

html:

<div id='content'>
mytext<div class="blink"></div>pharse
</div>

Upvotes: 1

Krunal Panchal
Krunal Panchal

Reputation: 788

Here is your answer

CODE

HTML:

<div id="www">mytextpharse<div class="blink"></div></div>

JQUERY

$(document).ready(function(){
    $pos = 3
    $("body").keydown(function(e) {
          if(e.keyCode == 37) { 
              if($pos > 1){ pos($pos-1);$pos--}
              else{pos(3);$pos = 3; }
          }else if(e.keyCode == 39) { 
          if($pos < 3){ pos($pos+1); $pos++
          }else{
              pos(1); $pos= 1
          }
          }
    });

    function pos($step){
        console.log($step)
        switch($step){
            case 1:
                 $('#www').html('<div class="blink"></div>mytextpharse')
            break;
            case 2:
                 $('#www').html('mytext<div class="blink"></div>pharse')
            break;
            case 3:
                 $('#www').html('mytextpharse<div class="blink"></div>')
            break;
        }
    }
})

Fiddle http://jsfiddle.net/krunalp1993/zEazF/2/

Hope it helps you :)

Upvotes: 0

Related Questions